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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$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();
}

$search_results = [];
$search_performed = false;

// Handle AJAX search
if (isset($_GET['ajax']) && $_GET['ajax'] === '1') {
    header('Content-Type: application/json');
    
    $search_term = isset($_GET['term']) ? trim($_GET['term']) : '';
    $search_type = isset($_GET['type']) ? $_GET['type'] : 'all';
    
    if (strlen($search_term) >= 2) {
        $results = [];
        
        if ($search_type === 'all' || $search_type === 'name') {
            $sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, 
                           u.date_of_birth, u.gender, p.registration_type, p.is_active,
                           TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
                    FROM patients p
                    INNER JOIN users u ON p.user_id = u.user_id
                    WHERE u.full_name LIKE ?
                    LIMIT 10";
            
            $stmt = $conn->prepare($sql);
            $search_param = "%{$search_term}%";
            $stmt->bind_param("s", $search_param);
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $results[] = $row;
            }
        }
        
        echo json_encode(['success' => true, 'results' => $results]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Search term must be at least 2 characters']);
    }
    exit();
}

// Handle form search
if ($_SERVER['REQUEST_METHOD'] === 'POST' || isset($_GET['search'])) {
    $search_term = isset($_POST['search_term']) ? trim($_POST['search_term']) : (isset($_GET['search']) ? trim($_GET['search']) : '');
    $search_type = isset($_POST['search_type']) ? $_POST['search_type'] : 'all';
    
    if (!empty($search_term)) {
        $search_performed = true;
        
        $where_clauses = [];
        $params = [];
        $types = '';
        
        if ($search_type === 'name' || $search_type === 'all') {
            $where_clauses[] = "u.full_name LIKE ?";
            $params[] = "%{$search_term}%";
            $types .= 's';
        }
        
        if ($search_type === 'patient_number' || $search_type === 'all') {
            $where_clauses[] = "p.patient_number LIKE ?";
            $params[] = "%{$search_term}%";
            $types .= 's';
        }
        
        if ($search_type === 'phone' || $search_type === 'all') {
            $where_clauses[] = "(u.phone_primary LIKE ? OR u.phone_secondary LIKE ?)";
            $params[] = "%{$search_term}%";
            $params[] = "%{$search_term}%";
            $types .= 'ss';
        }
        
        $where_sql = implode(' OR ', $where_clauses);
        
        $sql = "SELECT 
                    p.patient_id, p.patient_number, p.registration_type, p.is_active,
                    u.full_name, u.phone_primary, u.email, u.gender, u.date_of_birth, u.address,
                    ip.provider_name,
                    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 u.full_name ASC
                LIMIT 50";
        
        $stmt = $conn->prepare($sql);
        if (!empty($types)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $search_results = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Search')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .search-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .search-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .search-icon {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            color: white;
            margin-bottom: 1rem;
        }
        
        .search-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .search-type-selector {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .search-type-btn {
            padding: 0.5rem 1.25rem;
            border: 2px solid #e2e8f0;
            background: white;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
            color: #64748b;
        }
        
        .search-type-btn.active {
            background: #3b82f6;
            border-color: #3b82f6;
            color: white;
        }
        
        .search-input-group {
            position: relative;
            max-width: 600px;
            margin: 0 auto;
        }
        
        .search-input {
            width: 100%;
            padding: 1rem 3.5rem 1rem 1.5rem;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 1.125rem;
        }
        
        .search-btn {
            position: absolute;
            right: 0.5rem;
            top: 50%;
            transform: translateY(-50%);
            padding: 0.75rem 1.5rem;
            background: #3b82f6;
            border: none;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            cursor: pointer;
        }
        
        .patient-result-card {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .patient-name {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .patient-details-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .detail-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            font-size: 0.875rem;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            margin-right: 0.5rem;
            margin-top: 1rem;
        }
        
        .btn-view {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .btn-medical {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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 Search</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"><a href="list_patients.php">Patients</a></li>
                                        <li class="breadcrumb-item active">Search</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="search-card">
                        <div class="search-header">
                            <div class="search-icon">
                                <i class="ri-search-line"></i>
                            </div>
                            <h2 class="search-title">Find a Patient</h2>
                            <p style="color: #64748b;">Search by name, patient number, or phone</p>
                        </div>
                        
                        <form method="POST" id="searchForm">
                            <div class="search-type-selector">
                                <button type="button" class="search-type-btn active" data-type="all">
                                    <i class="ri-global-line"></i> All
                                </button>
                                <button type="button" class="search-type-btn" data-type="name">
                                    <i class="ri-user-line"></i> Name
                                </button>
                                <button type="button" class="search-type-btn" data-type="patient_number">
                                    <i class="ri-hashtag"></i> Patient Number
                                </button>
                                <button type="button" class="search-type-btn" data-type="phone">
                                    <i class="ri-phone-line"></i> Phone
                                </button>
                            </div>
                            
                            <input type="hidden" name="search_type" id="searchType" value="all">
                            
                            <div class="search-input-group">
                                <input type="text" 
                                       class="search-input" 
                                       name="search_term" 
                                       id="searchInput"
                                       placeholder="Start typing to search..." 
                                       value="<?php echo htmlspecialchars($search_term ?? ''); ?>">
                                <button type="submit" class="search-btn">
                                    <i class="ri-search-line"></i> Search
                                </button>
                            </div>
                        </form>
                    </div>

                    <?php if ($search_performed): ?>
                    <div style="background: white; border-radius: 12px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);">
                        <div style="padding: 1.5rem; border-bottom: 1px solid #e2e8f0;">
                            <h5>Search Results (<?php echo count($search_results); ?> found)</h5>
                        </div>
                        
                        <?php if (!empty($search_results)): ?>
                            <div style="padding: 1.5rem;">
                                <?php foreach ($search_results as $patient): ?>
                                <div class="patient-result-card">
                                    <div class="patient-name"><?php echo htmlspecialchars($patient['full_name']); ?></div>
                                    <div style="color: #3b82f6; font-weight: 600; font-family: monospace;">
                                        <?php echo htmlspecialchars($patient['patient_number']); ?>
                                    </div>
                                    
                                    <div class="patient-details-grid">
                                        <div class="detail-item">
                                            <i class="ri-phone-line"></i>
                                            <span><?php echo htmlspecialchars($patient['phone_primary']); ?></span>
                                        </div>
                                        <div class="detail-item">
                                            <i class="ri-calendar-line"></i>
                                            <span><?php echo $patient['age']; ?> years / <?php echo ucfirst(strtolower($patient['gender'])); ?></span>
                                        </div>
                                        <?php if ($patient['provider_name']): ?>
                                        <div class="detail-item">
                                            <i class="ri-shield-check-line"></i>
                                            <span><?php echo htmlspecialchars($patient['provider_name']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <div>
                                        <a href="patient_profile.php?id=<?php echo $patient['patient_id']; ?>" class="action-btn btn-view">
                                            <i class="ri-eye-line"></i> View Profile
                                        </a>
                                        <a href="medical_records.php?patient_id=<?php echo $patient['patient_id']; ?>" class="action-btn btn-medical">
                                            <i class="ri-file-list-3-line"></i> Medical Records
                                        </a>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                        <div class="empty-state">
                            <i class="ri-search-line" style="font-size: 3rem;"></i>
                            <h5>No Patients Found</h5>
                            <p>No patients match "<?php echo htmlspecialchars($search_term); ?>"</p>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </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>
    document.addEventListener('DOMContentLoaded', function() {
        const searchTypeBtns = document.querySelectorAll('.search-type-btn');
        const searchTypeInput = document.getElementById('searchType');
        
        searchTypeBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                searchTypeBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                searchTypeInput.value = this.getAttribute('data-type');
            });
        });
    });
    </script>

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