<?php
include "config.php";

$id=$_GET['id'];

$a=mysqli_fetch_assoc(
mysqli_query($conn,"SELECT * FROM appointments WHERE id='$id'")
);

$name=$a['patient_name'];
$mobile=$a['mobile'];
$age=$a['age'];
$date=$a['visit_date'];

/* Check Patient */
$p=mysqli_query($conn,"SELECT id FROM patients WHERE mobile='$mobile'");

if(mysqli_num_rows($p)>0){
$row=mysqli_fetch_assoc($p);
$patient_id=$row['id'];
}else{
mysqli_query($conn,"
INSERT INTO patients(name,age,mobile)
VALUES('$name','$age','$mobile')
");
$patient_id=mysqli_insert_id($conn);
}

/* Token Number */
$t=mysqli_fetch_assoc(
mysqli_query($conn,"
SELECT MAX(token_no) AS t FROM opd_tokens WHERE visit_date='$date'
")
);

$token = $t['t'] + 1;

/* Insert Token */
mysqli_query($conn,"
INSERT INTO opd_tokens(patient_id,token_no,visit_date)
VALUES('$patient_id','$token','$date')
");

/* Update Appointment */
mysqli_query($conn,"
UPDATE appointments SET status='Approved' WHERE id='$id'
");

header("Location: appointments.php");