<?php
session_start();
require_once __DIR__ . '/../../dripend/includes/db.php';

// Validate ID
if (!isset($_GET['id'])) {
    die("Invalid request");
}
$id = intval($_GET['id']);

// Lookup loader
function fetchLookup($conn, $table, $idField = 'id', $nameField = null) {
    if (!$nameField) $nameField = $idField;
    $data = [];
    $res = $conn->query("SELECT $idField, $nameField FROM $table ORDER BY $nameField ASC");
    while ($row = $res->fetch_assoc()) {
        $data[$row[$idField]] = $row[$nameField];
    }
    return $data;
}

// Load lookups
$prefixes    = fetchLookup($conn,'prefix','id','prefix_name');
$genders     = fetchLookup($conn,'gender','id','gender_name');
$staffs      = fetchLookup($conn,'staff_status','id','status_name');
$children    = fetchLookup($conn,'child_status','id','child_name');
$insurances  = fetchLookup($conn,'insurance_type','id','insurance_name');
$occupations = fetchLookup($conn,'occupation','id','occupation_name');
$languages   = fetchLookup($conn,'languages','id','language_name');
$educations  = fetchLookup($conn,'education_level','id','education_name');
$maritals    = fetchLookup($conn,'marital_status','id','status_name');
$relations   = fetchLookup($conn,'emergency_relation','id','relation_name');
$religions   = fetchLookup($conn,'religion','id','religion_name');

// Fetch patient
$stmt = $conn->prepare("SELECT * FROM patient WHERE id=?");
$stmt->bind_param("i",$id);
$stmt->execute();
$p = $stmt->get_result()->fetch_assoc();

if (!$p) die("Patient not found");

// UPDATE LOGIC
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

$stmt = $conn->prepare("
UPDATE patient SET
prefix=?, first_name=?, middle_name=?, last_name=?, gender_id=?, mobile=?, dob=?, age=?,
staff_status_id=?, child_status_id=?, nhis_no=?, other_insurance_id=?, other_insurance_no=?,
moh_no=?, ghana_card_no=?, occupation_id=?, language_id=?, education_id=?, email=?,
marital_status_id=?, scheme_code=?, tracking_no=?, emergency_name=?, emergency_number=?,
emergency_address=?, emergency_relation_id=?, patient_address=?, religion=?, card_serial=?
WHERE id=?
");

$stmt->bind_param(
"isssissiiissssssissssssissssi",
$_POST['prefix'],
$_POST['first_name'],
$_POST['middle_name'],
$_POST['last_name'],
$_POST['gender_id'],
$_POST['mobile'],
$_POST['dob'],
$_POST['age'],
$_POST['staff_status_id'],
$_POST['child_status_id'],
$_POST['nhis_no'],
$_POST['other_insurance_id'],
$_POST['other_insurance_no'],
$_POST['moh_no'],
$_POST['ghana_card_no'],
$_POST['occupation_id'],
$_POST['language_id'],
$_POST['education_id'],
$_POST['email'],
$_POST['marital_status_id'],
$_POST['scheme_code'],
$_POST['tracking_no'],
$_POST['emergency_name'],
$_POST['emergency_number'],
$_POST['emergency_address'],
$_POST['emergency_relation_id'],
$_POST['patient_address'],
$_POST['religion'],
$_POST['card_serial'],
$id
);

if ($stmt->execute()) {
    echo "<script>
        alert('Patient updated successfully');
        window.location.href='totalPatientReport.php';
    </script>";
    exit;
} else {
    echo "<p style='color:red;'>Update failed: {$stmt->error}</p>";
}
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Edit Patient</title>

<style>
body{font-family:Segoe UI;background:#f5f7fa;}

.modal{
display:flex;
align-items:center;
justify-content:center;
height:100vh;
background:rgba(0,0,0,0.6);
}

.container{
background:#fff;
width:95%;
max-width:1100px;
padding:20px;
border-radius:10px;
max-height:90vh;
overflow:auto;
}

form{
display:grid;
grid-template-columns:repeat(auto-fit,minmax(280px,1fr));
gap:14px;
}

label{font-weight:600;font-size:13px;}
input,select{padding:8px;border:1px solid #ccc;border-radius:6px;}

.section{
grid-column:1/-1;
background:#0077b6;
color:#fff;
padding:8px;
border-radius:6px;
font-weight:bold;
}

.actions{
grid-column:1/-1;
display:flex;
justify-content:flex-end;
gap:10px;
}

.btn{
padding:10px 16px;
border:none;
border-radius:6px;
color:#fff;
cursor:pointer;
}

.btn-update{background:#2a9d8f;}
.btn-close{background:#6c757d;}
</style>
</head>

<body>

<div class="modal">
<div class="container">

<h2>Edit Patient Record</h2>

<form method="post">

<!-- Patient No -->
<label>Patient No</label>
<input type="text" value="<?php echo $p['patient_no']; ?>" readonly>

<label>Prefix</label>
<select name="prefix">
<?php foreach($prefixes as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['prefix']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>First Name</label>
<input name="first_name" value="<?php echo $p['first_name']; ?>">

<label>Middle Name</label>
<input name="middle_name" value="<?php echo $p['middle_name']; ?>">

<label>Last Name</label>
<input name="last_name" value="<?php echo $p['last_name']; ?>">

<label>Gender</label>
<select name="gender_id">
<?php foreach($genders as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['gender_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Mobile</label>
<input name="mobile" value="<?php echo $p['mobile']; ?>">

<label>DOB</label>
<input type="date" name="dob" value="<?php echo $p['dob']; ?>">

<label>Age</label>
<input name="age" value="<?php echo $p['age']; ?>">

<label>Staff Status</label>
<select name="staff_status_id">
<?php foreach($staffs as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['staff_status_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Child Status</label>
<select name="child_status_id">
<?php foreach($children as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['child_status_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<div class="section">Insurance</div>

<label>NHIS</label>
<input name="nhis_no" value="<?php echo $p['nhis_no']; ?>">

<label>Insurance</label>
<select name="other_insurance_id">
<?php foreach($insurances as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['other_insurance_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Insurance No</label>
<input name="other_insurance_no" value="<?php echo $p['other_insurance_no']; ?>">

<label>MOH No</label>
<input name="moh_no" value="<?php echo $p['moh_no']; ?>">

<label>Ghana Card</label>
<input name="ghana_card_no" value="<?php echo $p['ghana_card_no']; ?>">

<div class="section">Other Details</div>

<label>Occupation</label>
<select name="occupation_id">
<?php foreach($occupations as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['occupation_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Language</label>
<select name="language_id">
<?php foreach($languages as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['language_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Education</label>
<select name="education_id">
<?php foreach($educations as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['education_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Email</label>
<input name="email" value="<?php echo $p['email']; ?>">

<label>Marital Status</label>
<select name="marital_status_id">
<?php foreach($maritals as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['marital_status_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Scheme Code</label>
<input name="scheme_code" value="<?php echo $p['scheme_code']; ?>">

<label>Tracking No</label>
<input name="tracking_no" value="<?php echo $p['tracking_no']; ?>">

<div class="section">Emergency</div>

<label>Name</label>
<input name="emergency_name" value="<?php echo $p['emergency_name']; ?>">

<label>Number</label>
<input name="emergency_number" value="<?php echo $p['emergency_number']; ?>">

<label>Address</label>
<input name="emergency_address" value="<?php echo $p['emergency_address']; ?>">

<label>Relation</label>
<select name="emergency_relation_id">
<?php foreach($relations as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['emergency_relation_id']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Patient Address</label>
<input name="patient_address" value="<?php echo $p['patient_address']; ?>">

<label>Religion</label>
<select name="religion">
<?php foreach($religions as $k=>$v): ?>
<option value="<?php echo $k; ?>" <?php if($p['religion']==$k) echo 'selected'; ?>><?php echo $v; ?></option>
<?php endforeach; ?>
</select>

<label>Card Serial</label>
<input name="card_serial" value="<?php echo $p['card_serial']; ?>">

<div class="actions">
<button type="button" class="btn btn-close" onclick="window.history.back()">Close</button>
<button type="submit" class="btn btn-update">Update</button>
</div>

</form>

</div>
</div>

</body>
</html>