<?php
session_start();
if(!isset($_SESSION['admin'])){
header("Location:index.php");
exit();
}
include "config.php";
include "header.php";

$msg="";

if(isset($_POST['save'])){

$name = trim($_POST['name']);
$age = trim($_POST['age']);
$gender = $_POST['gender'];
$mobile = trim($_POST['mobile']);

# ================= VALIDATION =================

if(!preg_match("/^[a-zA-Z ]+$/",$name)){
  $msg="Invalid Name (letters only)";
}
elseif(!is_numeric($age) || $age<1 || $age>120){
  $msg="Invalid Age";
}
elseif(!preg_match("/^[0-9]{10}$/",$mobile)){
  $msg="Mobile must be 10 digits";
}
else{

# Check duplicate patient
$chk=mysqli_query($conn,"SELECT id FROM patients 
WHERE name='$name' AND mobile='$mobile'");

if(mysqli_num_rows($chk)>0){
   $msg="Patient already exists";
}
else{

mysqli_query($conn,
"INSERT INTO patients(name,age,gender,mobile)
VALUES('$name','$age','$gender','$mobile')");

$pid = mysqli_insert_id($conn);

$today=date("Y-m-d");

$r=mysqli_query($conn,"SELECT MAX(token_no) AS t 
FROM opd_tokens WHERE visit_date='$today'");
$d=mysqli_fetch_assoc($r);
$token = $d['t'] + 1;

mysqli_query($conn,
"INSERT INTO opd_tokens(patient_id,token_no,visit_date)
VALUES('$pid','$token','$today')");

$msg="Patient Added Successfully";

}

}
}
?>

<h4>Add Patient</h4>

<?php if($msg!=""){ ?>
<div class="alert alert-info"><?php echo $msg; ?></div>
<?php } ?>

<form method="post">

<input class="form-control mb-2"
name="name"
placeholder="Patient Name"
pattern="[A-Za-z ]+"
title="Letters only"
required>

<input class="form-control mb-2"
name="age"
type="number"
min="1"
max="120"
placeholder="Age"
required>

<select class="form-control mb-2" name="gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>

<input class="form-control mb-2"
name="mobile"
placeholder="Mobile Number"
pattern="[0-9]{10}"
title="Enter 10 digit mobile number"
maxlength="10"
required>

<button class="btn btn-success" name="save">Save</button>

</form>

<?php include "footer.php"; ?>