<?php
session_start();
include('includes/db.php');
include('includes/header.php');

// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

/* ================= HELPER ================= */
// Safe htmlspecialchars wrapper
function e($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

// Calculate age
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') return '';
    $dobDate = new DateTime($dob);
    $now = new DateTime();
    $diff = $now->diff($dobDate);

    if ($diff->y >= 1) {
        return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
    } else {
        return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
    }
}

// ---------------- Get patient ID ----------------
$patient_id = intval($_GET['id'] ?? 0);
if ($patient_id <= 0) {
    $_SESSION['flash'] = ['message'=>'Invalid patient ID','color'=>'#dc3545'];
    header("Location: patients.php");
    exit;
}

// ---------------- Fetch patient data ----------------
$stmt = $pdo->prepare("
    SELECT p.*, f.name as facility_name
    FROM patients p
    LEFT JOIN facility f ON p.facility_id = f.id
    WHERE p.id = ?
");
$stmt->execute([$patient_id]);
$patient = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$patient) {
    $_SESSION['flash'] = ['message'=>'Patient not found','color'=>'#dc3545'];
    header("Location: patients.php");
    exit;
}

// ---------------- Sanitize all nulls ----------------
foreach ($patient as $key => $value) {
    if (is_null($value)) {
        $patient[$key] = '';
    }
}
?>

<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
    <div class="content-wrapper">
        <div class="col-xs-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Patient Details</h4>
                    <a href="all_patients.php" class="btn btn-outline-secondary btn-sm float-right">Back to List</a>
                </div>
                <div class="card-body collapse in">
                    <div class="card-block card-dashboard">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <tbody>
                                    <tr>
                                        <th>File ID</th>
                                        <td><?= e($patient['file_id']) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Full Name</th>
                                        <td>
                                            <?= e(trim($patient['first_name'] . ' ' . $patient['middle_name'] . ' ' . $patient['last_name'])) ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Gender & Age</th>
                                        <td>
                                            <div><?= e($patient['gender']) ?></div>
                                            <div><?= ($patient['d_o_b'] !== '' && $patient['d_o_b'] !== '0000-00-00') ? calculate_age($patient['d_o_b']) : '' ?></div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Date of Birth</th>
                                        <td><?= e($patient['d_o_b']) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Marital Status</th>
                                        <td><?= e($patient['marital_status']) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Nationality</th>
                                        <td><?= e($patient['nationality']) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Phone</th>
                                        <td>
                                            <div><?= e($patient['phone']) ?></div>
                                            <div><?= e($patient['secondary_phone']) ?></div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Emergency Contact</th>
                                        <td>
                                            <div><?= e($patient['emergency_contact_name']) ?></div>
                                            <div><?= e($patient['emergency_contact_phone']) ?></div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Address</th>
                                        <td>
                                            <div><?= e($patient['country']) ?></div>
                                            <div><?= e($patient['province']) ?></div>
                                            <div><?= e($patient['district']) ?></div>
                                            <div><?= e($patient['sector']) ?></div>
                                            <div><?= e($patient['cell']) ?></div>
                                            <div><?= e($patient['village']) ?></div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Created At</th>
                                        <td><?= e($patient['created_at']) ?></td>
                                    </tr>
                                    <tr>
                                        <th>Last Updated</th>
                                        <td><?= e($patient['updated_at']) ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="mt-3">
                            <a href="edit_patient.php?id=<?= e($patient['id']) ?>" class="btn btn-primary">Edit Patient</a>
                            <a href="all_patients.php" class="btn btn-secondary">Back to List</a>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include('includes/footer.php'); ?>
