<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 1. Database Connection
require_once __DIR__ . '/../../dripend/includes/db.php';

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b; font-family:sans-serif;'>Fatal Error: Database connection failed. Please check includes/db.php</div>");
}

// 2. Search Logic
$search_query = trim($_GET['q'] ?? '');
$patients = [];
$has_searched = false;

if ($search_query !== '') {
    $has_searched = true;
    // Prepare the search term with wildcards for partial matching
    $like_term = '%' . $search_query . '%';

    // Join the gender and insurance_type tables using the new schema
    $sql = "
        SELECT 
            p.patient_no, p.first_name, p.last_name, p.dob, p.mobile,
            g.gender_name,
            p.nhis_no, i.insurance_name,
            CASE 
                WHEN p.nhis_no IS NOT NULL AND p.nhis_no != '' THEN 'NHIS'
                WHEN p.other_insurance_id IS NOT NULL THEN 'Corporate'
                ELSE 'Cash'
            END AS payment_category
        FROM patient p
        LEFT JOIN gender g ON p.gender_id = g.id
        LEFT JOIN insurance_type i ON p.other_insurance_id = i.id
        WHERE p.patient_no LIKE ? 
           OR p.first_name LIKE ? 
           OR p.last_name LIKE ? 
           OR p.mobile LIKE ? 
           OR p.nhis_no LIKE ?
           OR CONCAT(p.first_name, ' ', p.last_name) LIKE ?
        ORDER BY p.first_name ASC 
        LIMIT 50
    ";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ssssss", $like_term, $like_term, $like_term, $like_term, $like_term, $like_term);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            // Calculate exact age dynamically
            if (!empty($row['dob'])) {
                $dob = new DateTime($row['dob']);
                $now = new DateTime();
                $row['age'] = $now->diff($dob)->y;
            } else {
                $row['age'] = 'N/A';
            }
            $patients[] = $row;
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Patient Directory | DripDental</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root {
  --sidebar-width: 240px;
  --e-blue: #1e3a8a;
  --e-blue-light: #eff6ff;
  --e-green: #10b981;
  --e-red: #ef4444;
  --e-gray: #f8fafc;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --border-color: #e2e8f0;
}

* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif; }
body { background: var(--e-gray); color: var(--text-main); overflow-x: hidden; }

/* Flush Page Wrapper */
.page-wrapper {
  position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width));
  min-height: 100vh; padding: 30px; display: block;
}

.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; border-bottom: 2px solid var(--border-color); padding-bottom: 15px; }
.page-title { font-size: 24px; font-weight: 800; color: var(--e-blue); text-transform: uppercase; display: flex; align-items: center; gap: 10px; }

.btn-new { background: var(--e-green); color: #fff; padding: 10px 20px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 14px; transition: 0.2s; box-shadow: 0 4px 6px rgba(16, 185, 129, 0.2); }
.btn-new:hover { background: #059669; transform: translateY(-2px); }

/* Search Hero Section */
.search-card {
  background: #ffffff; border: 1px solid var(--border-color); border-radius: 12px;
  padding: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.03); margin-bottom: 30px;
}
.search-card h2 { font-size: 16px; font-weight: 800; color: var(--e-blue); margin-bottom: 15px; }
.search-form { display: flex; gap: 10px; }
.search-input {
  flex: 1; padding: 15px 20px; font-size: 16px; border: 2px solid #cbd5e1; border-radius: 8px;
  outline: none; transition: 0.2s; color: var(--text-main); font-weight: 600;
}
.search-input:focus { border-color: var(--e-blue); box-shadow: 0 0 0 4px var(--e-blue-light); }
.btn-search {
  background: var(--e-blue); color: #fff; border: none; padding: 0 25px; border-radius: 8px;
  font-size: 15px; font-weight: 800; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 8px;
}
.btn-search:hover { background: #1e293b; }
.btn-clear {
  background: #f1f5f9; color: #475569; border: 1px solid #cbd5e1; padding: 0 20px; border-radius: 8px;
  font-size: 15px; font-weight: 700; cursor: pointer; transition: 0.2s; text-decoration: none; display: flex; align-items: center; justify-content: center;
}
.btn-clear:hover { background: #e2e8f0; color: #0f172a; }

/* Results Table */
.results-card { background: #ffffff; border: 1px solid var(--border-color); border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.03); }
.table-wrapper { overflow-x: auto; }
.master-table { width: 100%; border-collapse: collapse; text-align: left; }
.master-table th { background: #f1f5f9; padding: 15px 20px; font-size: 12px; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 2px solid var(--border-color); }
.master-table td { padding: 15px 20px; border-bottom: 1px solid var(--border-color); font-size: 14px; vertical-align: middle; }
.master-table tr:hover { background: #f8fafc; }

/* Patient Info Cell */
.pat-info { display: flex; align-items: center; gap: 12px; }
.pat-avatar { width: 40px; height: 40px; border-radius: 50%; background: var(--e-blue-light); color: var(--e-blue); display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 16px; }
.pat-name { font-weight: 800; color: var(--text-main); margin-bottom: 2px; }
.pat-id { font-size: 12px; font-weight: 700; color: var(--text-muted); }

/* Badges */
.badge { padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; text-transform: uppercase; display: inline-block; }
.badge-nhis { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; }
.badge-cash { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.badge-corp { background: #fef3c7; color: #b45309; border: 1px solid #fde68a; }

/* Action Buttons */
.action-group { display: flex; gap: 8px; }
.btn-action { padding: 8px 12px; border-radius: 6px; font-size: 12px; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; transition: 0.2s; border: 1px solid transparent; }
.btn-view { background: #f1f5f9; color: #334155; border-color: #cbd5e1; }
.btn-view:hover { background: #e2e8f0; color: #0f172a; }
.btn-book { background: var(--e-blue-light); color: var(--e-blue); border-color: #bfdbfe; }
.btn-book:hover { background: var(--e-blue); color: #fff; }

/* Empty States */
.empty-state { text-align: center; padding: 60px 20px; }
.empty-icon { font-size: 48px; color: #cbd5e1; margin-bottom: 15px; }
.empty-text { font-size: 18px; font-weight: 700; color: var(--text-muted); }

@media (max-width: 900px) {
  .page-wrapper { margin-left: 0; width: 100%; position: relative; }
  .search-form { flex-direction: column; }
  .btn-search, .btn-clear { justify-content: center; padding: 15px; }
}
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper">

    <div class="page-header">
        <h1 class="page-title"><i class="fa-solid fa-users"></i> Master Patient Index</h1>
        <a href="addNewPatient.php" class="btn-new">+ Register New Patient</a>
    </div>

    <div class="search-card">
        <h2>Find Patient Profile</h2>
        <form class="search-form" method="GET" action="search_patient.php">
            <input type="text" name="q" class="search-input" placeholder="Search by Name, Patient ID, Phone, or NHIS Number..." value="<?php echo htmlspecialchars($search_query); ?>" autocomplete="off" autofocus>
            <button type="submit" class="btn-search"><i class="fa-solid fa-magnifying-glass"></i> Search DB</button>
            <?php if ($has_searched): ?>
                <a href="search_patient.php" class="btn-clear"><i class="fa-solid fa-xmark"></i> Clear</a>
            <?php endif; ?>
        </form>
    </div>

    <div class="results-card">
        <?php if ($has_searched): ?>
            <?php if (count($patients) > 0): ?>
                <div class="table-wrapper">
                    <table class="master-table">
                        <thead>
                            <tr>
                                <th>Patient Identity</th>
                                <th>Demographics</th>
                                <th>Contact</th>
                                <th>Coverage</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($patients as $p): ?>
                            <tr>
                                <td>
                                    <div class="pat-info">
                                        <div class="pat-avatar"><?php echo strtoupper(substr($p['first_name'], 0, 1)); ?></div>
                                        <div>
                                            <div class="pat-name"><?php echo htmlspecialchars($p['first_name'] . ' ' . $p['last_name']); ?></div>
                                            <div class="pat-id"><?php echo htmlspecialchars($p['patient_no']); ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <strong><?php echo $p['age']; ?> Yrs</strong><br>
                                    <span style="color:var(--text-muted); font-size:12px;"><?php echo htmlspecialchars($p['gender_name'] ?? 'NA'); ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($p['mobile']); ?></td>
                                <td>
                                    <?php if ($p['payment_category'] === 'NHIS'): ?>
                                        <span class="badge badge-nhis">NHIS</span><br>
                                        <span style="font-size:11px; color:var(--text-muted);"><?php echo htmlspecialchars($p['nhis_no']); ?></span>
                                    <?php elseif ($p['payment_category'] === 'Corporate'): ?>
                                        <span class="badge badge-corp"><?php echo htmlspecialchars($p['insurance_name']); ?></span>
                                    <?php else: ?>
                                        <span class="badge badge-cash">Cash Account</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-group">
                                        <a href="patientMedicalRecords.php?patient_id=<?php echo urlencode($p['patient_no']); ?>" class="btn-action btn-view">
                                            <i class="fa-solid fa-folder-open"></i> View Patient Record
                                        </a>
                                        <a href="../appointment/add_appointment.php?patient_id=<?php echo urlencode($p['patient_no']); ?>" class="btn-action btn-book">
                                            <i class="fa-solid fa-calendar-plus"></i> Book / Service
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="empty-state">
                    <i class="fa-solid fa-user-xmark empty-icon"></i>
                    <div class="empty-text">No patients found matching "<?php echo htmlspecialchars($search_query); ?>"</div>
                    <p style="color: var(--text-muted); margin-top: 10px; font-size: 14px;">Try searching with a different phone number or verify the spelling.</p>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fa-solid fa-hospital-user empty-icon"></i>
                <div class="empty-text">Enter a search term above to locate a patient.</div>
                <p style="color: var(--text-muted); margin-top: 10px; font-size: 14px;">You can search by system ID, phone number, name, or insurance ID.</p>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
    // Detects if the page was hard refreshed (F5 / Reload Button)
    if (String(window.performance.getEntriesByType("navigation")[0].type) === "reload") {
        // Redirects to the clean version of the page, stripping the ?q= URL parameters
        window.location.href = window.location.pathname;
    }
</script>

</body>
</html>