<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';
//include 'classes/JobQueueProcessor.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'NURSE', 'LAB_TECHNICIAN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$records_per_page = 20;
$offset = ($page - 1) * $records_per_page;

// Filters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$registration_type = isset($_GET['registration_type']) ? $_GET['registration_type'] : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';

// Build query
$where_clauses = ["u.user_type = 'PATIENT'"];
$params = [];
$types = '';

if (!empty($search)) {
    $where_clauses[] = "(u.full_name LIKE ? OR u.phone_primary LIKE ? OR u.email LIKE ? OR p.patient_number LIKE ?)";
    $search_param = "%{$search}%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $types .= 'ssss';
}

if (!empty($registration_type)) {
    $where_clauses[] = "p.registration_type = ?";
    $params[] = $registration_type;
    $types .= 's';
}

if (!empty($status)) {
    if ($status === 'ACTIVE') {
        $where_clauses[] = "p.is_active = 1";
    } else {
        $where_clauses[] = "p.is_active = 0";
    }
}

$where_sql = implode(' AND ', $where_clauses);

// Count total records
$count_sql = "SELECT COUNT(*) as total 
              FROM patients p 
              INNER JOIN users u ON p.user_id = u.user_id 
              WHERE {$where_sql}";

if (!empty($params)) {
    $count_stmt = $conn->prepare($count_sql);
    if (!empty($types)) {
        $count_stmt->bind_param($types, ...$params);
    }
    $count_stmt->execute();
    $total_records = $count_stmt->get_result()->fetch_assoc()['total'];
} else {
    $total_records = $conn->query($count_sql)->fetch_assoc()['total'];
}

$total_pages = ceil($total_records / $records_per_page);

// Fetch patients
$patients_sql = "SELECT 
                    p.patient_id,
                    p.patient_number,
                    p.registration_type,
                    p.is_active,
                    p.created_at,
                    u.user_id,
                    u.full_name,
                    u.phone_primary,
                    u.email,
                    u.gender,
                    u.date_of_birth,
                    ip.provider_name,
                    p.insurance_number,
                    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
                FROM patients p
                INNER JOIN users u ON p.user_id = u.user_id
                LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
                WHERE {$where_sql}
                ORDER BY p.created_at DESC
                LIMIT ? OFFSET ?";

$params[] = $records_per_page;
$params[] = $offset;
$types .= 'ii';

$stmt = $conn->prepare($patients_sql);
if (!empty($types)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$patients_result = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_patients,
                SUM(CASE WHEN registration_type = 'INSURANCE' THEN 1 ELSE 0 END) as insurance_patients,
                SUM(CASE WHEN registration_type = 'WALK_IN' THEN 1 ELSE 0 END) as walk_in_patients,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_patients
              FROM patients";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

//triggerJobProcessing($conn);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient List')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.3s;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-icon {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        
        .stats-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            margin: 0.5rem 0;
        }
        
        .stats-label {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        .custom-table {
            width: 100%;
            margin: 0;
        }
        
        .custom-table thead th {
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
            color: #475569;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            padding: 1rem;
            white-space: nowrap;
        }
        
        .custom-table tbody td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
            color: #334155;
        }
        
        .custom-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }
        
        .badge-insurance {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-walk-in {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-corporate {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-referral {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .badge-online {
            background: #e9d5ff;
            color: #6b21a8;
        }
        
        .badge-active {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-inactive {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .patient-avatar {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
            font-size: 0.875rem;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .action-btn:hover {
            transform: translateY(-1px);
        }
        
        .btn-view {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .btn-view:hover {
            background: #bfdbfe;
        }
        
        .btn-edit {
            background: #fef3c7;
            color: #92400e;
        }
        
        .btn-edit:hover {
            background: #fde68a;
        }
        
        .btn-medical {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .btn-medical:hover {
            background: #c7d2fe;
        }
        
        .pagination {
            margin: 1.5rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .pagination-info {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .pagination-controls {
            display: flex;
            gap: 0.5rem;
        }
        
        .page-btn {
            padding: 0.5rem 1rem;
            border: 1px solid #e2e8f0;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 0.875rem;
        }
        
        .page-btn:hover:not(:disabled) {
            background: #f8fafc;
            border-color: #cbd5e1;
        }
        
        .page-btn.active {
            background: #3b82f6;
            color: white;
            border-color: #3b82f6;
        }
        
        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }
        
        @media (max-width: 768px) {
            .stats-card {
                margin-bottom: 1rem;
            }
            
            .table-responsive {
                border-radius: 0;
            }
            
            .action-btn {
                padding: 0.25rem 0.5rem;
                font-size: 0.75rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Patient Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Patients</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #dbeafe;">
                                        <i class="ri-user-heart-line" style="color: #1e40af;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['total_patients']); ?></div>
                                        <div class="stats-label">Total Patients</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #d1fae5;">
                                        <i class="ri-shield-check-line" style="color: #065f46;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['insurance_patients']); ?></div>
                                        <div class="stats-label">Insurance Patients</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #fef3c7;">
                                        <i class="ri-wallet-line" style="color: #92400e;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['walk_in_patients']); ?></div>
                                        <div class="stats-label">Walk-in Patients</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #e0e7ff;">
                                        <i class="ri-check-double-line" style="color: #3730a3;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['active_patients']); ?></div>
                                        <div class="stats-label">Active Patients</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filter-card">
                        <form method="GET" id="filterForm">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" 
                                           value="<?php echo htmlspecialchars($search); ?>" 
                                           placeholder="Name, phone, email, patient number...">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Registration Type</label>
                                    <select class="form-select" name="registration_type">
                                        <option value="">All Types</option>
                                        <option value="INSURANCE" <?php echo $registration_type === 'INSURANCE' ? 'selected' : ''; ?>>Insurance</option>
                                        <option value="WALK_IN" <?php echo $registration_type === 'WALK_IN' ? 'selected' : ''; ?>>Walk-in</option>
                                        <option value="CORPORATE" <?php echo $registration_type === 'CORPORATE' ? 'selected' : ''; ?>>Corporate</option>
                                        <option value="REFERRAL" <?php echo $registration_type === 'REFERRAL' ? 'selected' : ''; ?>>Referral</option>
                                        <option value="ONLINE" <?php echo $registration_type === 'ONLINE' ? 'selected' : ''; ?>>Online</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status">
                                        <option value="">All Status</option>
                                        <option value="ACTIVE" <?php echo $status === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                        <option value="INACTIVE" <?php echo $status === 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end gap-2">
                                    <button type="submit" class="btn btn-primary flex-grow-1">
                                        <i class="ri-search-line me-1"></i> Search
                                    </button>
                                    <a href="list_patients.php" class="btn btn-secondary">
                                        <i class="ri-refresh-line"></i>
                                    </a>
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST'])): ?>
                                    <a href="register_patient.php" class="btn btn-success">
                                        <i class="ri-add-line me-1"></i> New Patient
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Patients Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h5 class="mb-0">
                                <i class="ri-file-list-3-line me-2"></i>
                                Patient List
                                <?php if ($total_records > 0): ?>
                                    <span class="text-muted" style="font-size: 0.875rem; font-weight: 400;">
                                        (<?php echo number_format($total_records); ?> patients)
                                    </span>
                                <?php endif; ?>
                            </h5>
                        </div>
                        
                        <div class="table-responsive">
                            <?php if ($patients_result->num_rows > 0): ?>
                            <table class="custom-table">
                                <thead>
                                    <tr>
                                        <th>Patient</th>
                                        <th>Patient Number</th>
                                        <th>Contact</th>
                                        <th>Age/Gender</th>
                                        <th>Registration</th>
                                        <th>Insurance</th>
                                        <th>Status</th>
                                        <th>Registered</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($patient = $patients_result->fetch_assoc()): 
                                        $initials = strtoupper(substr($patient['full_name'], 0, 2));
                                        $colors = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899'];
                                        $color = $colors[ord($initials[0]) % count($colors)];
                                    ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="patient-avatar" style="background: <?php echo $color; ?>;">
                                                    <?php echo $initials; ?>
                                                </div>
                                                <div class="ms-3">
                                                    <div style="font-weight: 600; color: #1e293b;">
                                                        <?php echo htmlspecialchars($patient['full_name']); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span style="font-family: monospace; font-weight: 600; color: #3b82f6;">
                                                <?php echo htmlspecialchars($patient['patient_number']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div style="font-size: 0.875rem;">
                                                <div><i class="ri-phone-line me-1"></i><?php echo htmlspecialchars($patient['phone_primary']); ?></div>
                                                <?php if ($patient['email']): ?>
                                                <div class="text-muted"><i class="ri-mail-line me-1"></i><?php echo htmlspecialchars($patient['email']); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div><?php echo $patient['age']; ?> years</div>
                                            <div class="text-muted" style="font-size: 0.875rem;">
                                                <?php echo ucfirst(strtolower($patient['gender'])); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php
                                            $reg_class = 'badge-walk-in';
                                            if ($patient['registration_type'] === 'INSURANCE') $reg_class = 'badge-insurance';
                                            elseif ($patient['registration_type'] === 'CORPORATE') $reg_class = 'badge-corporate';
                                            elseif ($patient['registration_type'] === 'REFERRAL') $reg_class = 'badge-referral';
                                            elseif ($patient['registration_type'] === 'ONLINE') $reg_class = 'badge-online';
                                            ?>
                                            <span class="badge <?php echo $reg_class; ?>">
                                                <?php echo str_replace('_', ' ', $patient['registration_type']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($patient['provider_name']): ?>
                                                <div style="font-size: 0.875rem;">
                                                    <div><?php echo htmlspecialchars($patient['provider_name']); ?></div>
                                                    <div class="text-muted"><?php echo htmlspecialchars($patient['insurance_number']); ?></div>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge <?php echo $patient['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                                <?php echo $patient['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-size: 0.875rem;">
                                                <?php echo date('d M Y', strtotime($patient['created_at'])); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex gap-1">
                                                <!-- New Visit Button -->
                                                <a href="create_patient_visit.php?patient_id=<?php echo $patient['patient_id']; ?>" 
                                                   class="action-btn" 
                                                   style="background: #dcfce7; color: #166534;"
                                                   title="New Visit">
                                                    <i class="ri-hospital-line"></i>
                                                </a>
                                                <a href="patient_profile.php?id=<?php echo $patient['patient_id']; ?>" 
                                                   class="action-btn btn-view" title="View Profile">
                                                    <i class="ri-eye-line"></i>
                                                </a>
                                                <a href="medical_records.php?patient_id=<?php echo $patient['patient_id']; ?>" 
                                                   class="action-btn btn-medical" title="Medical Records">
                                                    <i class="ri-file-list-3-line"></i>
                                                </a>
                                                <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                                <a href="edit_patient.php?id=<?php echo $patient['patient_id']; ?>" 
                                                   class="action-btn btn-edit" title="Edit">
                                                    <i class="ri-edit-line"></i>
                                                </a>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                            <div class="empty-state">
                                <i class="ri-user-search-line"></i>
                                <h5>No Patients Found</h5>
                                <p class="text-muted">
                                    <?php if (!empty($search) || !empty($registration_type) || !empty($status)): ?>
                                        No patients match your search criteria. Try adjusting your filters.
                                    <?php else: ?>
                                        No patients have been registered yet.
                                    <?php endif; ?>
                                </p>
                                <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST'])): ?>
                                <a href="register_patient.php" class="btn btn-primary mt-3">
                                    <i class="ri-add-line me-1"></i> Register First Patient
                                </a>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($total_pages > 1): ?>
                        <div class="pagination">
                            <div class="pagination-info">
                                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo number_format($total_records); ?> patients
                            </div>
                            <div class="pagination-controls">
                                <?php if ($page > 1): ?>
                                <a href="?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($registration_type) ? '&registration_type=' . $registration_type : ''; ?><?php echo !empty($status) ? '&status=' . $status : ''; ?>" 
                                   class="page-btn">
                                    <i class="ri-arrow-left-s-line"></i> Previous
                                </a>
                                <?php endif; ?>
                                
                                <?php
                                $start_page = max(1, $page - 2);
                                $end_page = min($total_pages, $page + 2);
                                
                                for ($i = $start_page; $i <= $end_page; $i++):
                                ?>
                                <a href="?page=<?php echo $i; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($registration_type) ? '&registration_type=' . $registration_type : ''; ?><?php echo !empty($status) ? '&status=' . $status : ''; ?>" 
                                   class="page-btn <?php echo $i === $page ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                                <?php endfor; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                <a href="?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo !empty($registration_type) ? '&registration_type=' . $registration_type : ''; ?><?php echo !empty($status) ? '&status=' . $status : ''; ?>" 
                                   class="page-btn">
                                    Next <i class="ri-arrow-right-s-line"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Auto-submit form on filter change
        const filterSelects = document.querySelectorAll('#filterForm select');
        filterSelects.forEach(select => {
            select.addEventListener('change', function() {
                document.getElementById('filterForm').submit();
            });
        });
        
        // Search on Enter key
        const searchInput = document.querySelector('input[name="search"]');
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>