<?php
/**
 * Patient Search Page
 * Generic patient search page that can handle different actions
 */

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

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

$action = isset($_GET['action']) ? $_GET['action'] : 'search';
$selected_patient_id = isset($_GET['patient_id']) ? intval($_GET['patient_id']) : 0;

// Get selected patient details if provided
$selected_patient = null;
if ($selected_patient_id > 0) {
    $patient_sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, 
                           u.email, u.date_of_birth, u.gender, p.registration_type
                    FROM patients p
                    INNER JOIN users u ON p.user_id = u.user_id
                    WHERE p.patient_id = ? AND p.is_active = 1";
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param("i", $selected_patient_id);
    $stmt->execute();
    $selected_patient = $stmt->get_result()->fetch_assoc();
}

// Handle different actions
$page_title = "Search Patient";
$action_title = "Search Patient";
$redirect_url = "";

switch ($action) {
    case 'hearing_aid_fitting':
        $page_title = "Select Patient for Hearing Aid Fitting";
        $action_title = "Hearing Aid Fitting";
        $redirect_url = "hearing_aid_fitting_form.php";
        break;
    case 'consultation':
        $page_title = "Select Patient for Consultation";
        $action_title = "New Consultation";
        $redirect_url = "new_consultation.php";
        break;
    case 'appointment':
        $page_title = "Select Patient for Appointment";
        $action_title = "Book Appointment";
        $redirect_url = "book_appointment.php";
        break;
    default:
        $page_title = "Search Patient";
        $action_title = "Search";
        $redirect_url = "patient_profile.php";
        break;
}

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .search-container {
            max-width: 800px;
            margin: 0 auto;
        }
        .patient-result-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .patient-result-card:hover {
            background: #f8fafc;
            border-color: #3b82f6;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .patient-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .patient-details {
            flex: 1;
        }
        .patient-name {
            font-weight: 600;
            font-size: 1.1rem;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        .patient-meta {
            color: #64748b;
            font-size: 0.875rem;
        }
    </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"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="search-container">
                                        <div class="mb-4">
                                            <h5 class="mb-3"><?php echo $action_title; ?></h5>
                                            <p class="text-muted">Search for a patient by name, patient number, phone number, or email</p>
                                        </div>
                                        
                                        <!-- Search Input -->
                                        <div class="input-group input-group-lg mb-4">
                                            <span class="input-group-text">
                                                <i class="ri-search-line"></i>
                                            </span>
                                            <input type="text" 
                                                   class="form-control" 
                                                   id="patientSearch" 
                                                   placeholder="Type patient name, number, phone, or email..."
                                                   autocomplete="off">
                                            <button class="btn btn-primary" type="button" onclick="searchPatients()">
                                                <i class="ri-search-line me-1"></i> Search
                                            </button>
                                        </div>
                                        
                                        <div class="text-center mb-3">
                                            <a href="register_patient.php" class="btn btn-outline-success">
                                                <i class="ri-user-add-line me-1"></i> Register New Patient
                                            </a>
                                        </div>
                                        
                                        <!-- Search Results -->
                                        <div id="searchResults" style="display: none;">
                                            <h6 class="mb-3">Search Results</h6>
                                            <div id="searchResultsList"></div>
                                        </div>
                                        
                                        <!-- Selected Patient Info -->
                                        <?php if ($selected_patient): ?>
                                        <div class="alert alert-info">
                                            <h6>Selected Patient:</h6>
                                            <p class="mb-0">
                                                <strong><?php echo htmlspecialchars($selected_patient['full_name']); ?></strong><br>
                                                Patient #: <?php echo htmlspecialchars($selected_patient['patient_number']); ?><br>
                                                Phone: <?php echo htmlspecialchars($selected_patient['phone_primary'] ?? 'N/A'); ?>
                                            </p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        const action = '<?php echo $action; ?>';
        const redirectUrl = '<?php echo $redirect_url; ?>';
        
        // Search on Enter key
        $('#patientSearch').on('keypress', function(e) {
            if (e.which === 13) {
                searchPatients();
            }
        });
        
        function searchPatients() {
            const query = $('#patientSearch').val().trim();
            
            if (query.length < 2) {
                Swal.fire({
                    icon: 'info',
                    title: 'Search Term Too Short',
                    text: 'Please enter at least 2 characters to search',
                    confirmButtonColor: '#3b82f6'
                });
                return;
            }
            
            // Show loading
            $('#searchResultsList').html('<div class="text-center"><i class="ri-loader-4-line spin"></i> Searching...</div>');
            $('#searchResults').show();
            
            $.ajax({
                url: 'ajax/search_patients.php',
                type: 'POST',
                data: { query: query },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.results && response.results.length > 0) {
                        let html = '';
                        response.results.forEach(patient => {
                            html += `
                                <div class="patient-result-card" onclick="selectPatient(${patient.id})">
                                    <div class="patient-info">
                                        <div class="patient-details">
                                            <div class="patient-name">${patient.full_name}</div>
                                            <div class="patient-meta">
                                                Patient #: ${patient.patient_number} | 
                                                ${patient.age || 'Age N/A'} | 
                                                ${patient.gender || 'N/A'} | 
                                                ${patient.phone_primary || patient.phone || 'No phone'}
                                            </div>
                                        </div>
                                        <button class="btn btn-sm btn-primary">
                                            <i class="ri-arrow-right-line"></i> Select
                                        </button>
                                    </div>
                                </div>
                            `;
                        });
                        $('#searchResultsList').html(html);
                    } else {
                        $('#searchResultsList').html('<div class="alert alert-info">No patients found matching your search.</div>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Search error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Search Error',
                        text: 'Failed to search patients. Please try again.',
                        confirmButtonColor: '#dc3545'
                    });
                    $('#searchResultsList').html('<div class="alert alert-danger">Error searching patients. Please try again.</div>');
                }
            });
        }
        
        function selectPatient(patientId) {
            if (!patientId) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Invalid patient ID',
                    confirmButtonColor: '#dc3545'
                });
                return;
            }
            
            // Redirect based on action
            let url = redirectUrl;
            if (url.includes('?')) {
                url += '&patient_id=' + patientId;
            } else {
                url += '?patient_id=' + patientId;
            }
            
            // Add action parameter if needed
            if (action && action !== 'search') {
                if (url.includes('?')) {
                    url += '&action=' + action;
                } else {
                    url += '?action=' + action;
                }
            }
            
            window.location.href = url;
        }
        
        // Auto-focus search input
        $(document).ready(function() {
            $('#patientSearch').focus();
        });
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>
