<?php
session_start();
require_once '../config.php';

requireAdmin();

$page_title = 'Manage Patients';

// Get all patients with search functionality
$search = clean($_GET['search'] ?? '');
$patients_query = "
    SELECT p.*, COUNT(a.id) as total_appointments
    FROM patients p
    LEFT JOIN appointments a ON p.id = a.patient_id
";

if ($search) {
    $patients_query .= " WHERE (p.full_name LIKE ? OR p.email LIKE ? OR p.health_id LIKE ?)";
}

$patients_query .= " GROUP BY p.id ORDER BY p.created_at DESC";

$patients_stmt = $conn->prepare($patients_query);
if ($search) {
    $search_param = "%$search%";
    $patients_stmt->bind_param('sss', $search_param, $search_param, $search_param);
}
$patients_stmt->execute();
$patients = $patients_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get statistics
$stats = [
    'total_patients' => $conn->query("SELECT COUNT(*) as count FROM patients")->fetch_assoc()['count'],
    'this_month' => $conn->query("SELECT COUNT(*) as count FROM patients WHERE MONTH(created_at) = MONTH(NOW())")->fetch_assoc()['count'],
    'active_appointments' => $conn->query("SELECT COUNT(*) as count FROM appointments WHERE status = 'confirmed'")->fetch_assoc()['count']
];

include 'header.php';
?>

                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">
                        <i class="fas fa-users text-primary"></i> All Patients (<?= count($patients) ?>)
                    </h1>
                </div>

                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-6 col-xl-4">
                        <div class="stat-card card bg-primary text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?= number_format($stats['total_patients']) ?></h4>
                                        <p class="card-text">Total Patients</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-users fa-2x opacity-75"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-xl-4">
                        <div class="stat-card card bg-success text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?= number_format($stats['this_month']) ?></h4>
                                        <p class="card-text">New This Month</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-user-plus fa-2x opacity-75"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-xl-4">
                        <div class="stat-card card bg-info text-white">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?= number_format($stats['active_appointments']) ?></h4>
                                        <p class="card-text">Active Appointments</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-check fa-2x opacity-75"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Search Form -->
                <div class="row mb-3">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <form method="GET" class="d-flex gap-2">
                                    <input type="text" name="search" class="form-control" placeholder="Search by name, email, or health ID..." value="<?= htmlspecialchars($search) ?>">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i> Search
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Patients Management -->
                <div class="card">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-list"></i> Patient List
                        </h5>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Patient Info</th>
                                    <th>Health ID</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th>Gender</th>
                                    <th>Appointments</th>
                                    <th>Registered</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($patients)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted py-4">
                                            <i class="fas fa-users fa-2x mb-2"></i><br>
                                            <?= $search ? 'No matching patients found' : 'No patients available' ?>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($patients as $patient): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <?php if ($patient['profile_photo'] ?? false): ?>
                                                        <img src="<?= SITE_URL ?>/<?= $patient['profile_photo'] ?>" alt="<?= htmlspecialchars($patient['full_name']) ?>" class="rounded-circle me-2" width="35" height="35">
                                                    <?php else: ?>
                                                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 35px; height: 35px; font-size: 16px;">
                                                            <i class="fas fa-user"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                    <strong><?= htmlspecialchars($patient['full_name']) ?></strong>
                                                </div>
                                            </td>
                                            <td>
                                                <code><?= htmlspecialchars($patient['health_id']) ?></code>
                                            </td>
                                            <td>
                                                <small><?= htmlspecialchars($patient['email']) ?></small>
                                            </td>
                                            <td>
                                                <small><?= htmlspecialchars($patient['phone'] ?? 'N/A') ?></small>
                                            </td>
                                            <td>
                                                <small>
                                                    <i class="fas fa-<?= ($patient['gender'] ?? '') === 'male' ? 'mars' : 'venus' ?>"></i>
                                                    <?= ucfirst($patient['gender'] ?? 'N/A') ?>
                                                </small>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?= $patient['total_appointments'] ?? 0 ?></span>
                                            </td>
                                            <td>
                                                <small><?= date('M d, Y', strtotime($patient['created_at'])) ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="patient-details.php?id=<?= $patient['id'] ?>" class="btn btn-outline-primary" title="View Profile">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <button class="btn btn-outline-danger" onclick="return confirm('Delete this patient?')" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

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