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

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

$patient_id = $_GET['patient_id'] ?? 0;

// Get patient details
$patient_query = "SELECT 
    p.*,
    u.full_name,
    u.phone_primary,
    u.phone_secondary,
    u.email,
    u.national_id,
    u.address,
    u.date_of_birth,
    u.gender
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
WHERE p.patient_id = ?";

$stmt = $conn->prepare($patient_query);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$patient = $stmt->get_result()->fetch_assoc();

if (!$patient) {
    $_SESSION['error_message'] = "Patient not found";
    header('Location: patient_search.php');
    exit();
}

// Calculate age
$age = 'N/A';
if (!empty($patient['date_of_birth'])) {
    $dob = new DateTime($patient['date_of_birth']);
    $now = new DateTime();
    $age = $dob->diff($now)->y;
}

// Get consultation statistics
$stats_query = "SELECT 
    COUNT(*) as total_consultations,
    COUNT(DISTINCT doctor_id) as doctors_seen,
    MAX(started_at) as last_visit,
    MIN(started_at) as first_visit
FROM consultations
WHERE patient_id = ?";

$stats_stmt = $conn->prepare($stats_query);
$stats_stmt->bind_param("i", $patient_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Patient Medical History')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .patient-header {
            background: linear-gradient(135deg, #2d7a2d, #26a69a);
            border-radius: 10px;
            padding: 2rem;
            color: white;
            margin-bottom: 2rem;
        }
        
        .patient-avatar-xl {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: rgba(255,255,255,0.2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 2.5rem;
            border: 3px solid rgba(255,255,255,0.3);
        }
        
        .info-card {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .timeline {
            position: relative;
            padding-left: 30px;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 2rem;
            border-left: 2px solid #e9ecef;
        }
        
        .timeline-item:last-child {
            border-left: 0;
        }
        
        .timeline-marker {
            position: absolute;
            left: -8px;
            top: 0;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            background: #2d7a2d;
            border: 3px solid white;
            box-shadow: 0 0 0 2px #2d7a2d;
        }
        
        .timeline-content {
            margin-left: 20px;
        }
        
        .allergy-badge {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            display: inline-block;
            margin: 0.25rem;
        }
        
        .vital-sign {
            text-align: center;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
        
        .vital-sign-value {
            font-size: 1.5rem;
            font-weight: bold;
            color: #2d7a2d;
        }
    </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 Medical History</h4>
                                <div class="page-title-right">
                                    <a href="patient_search.php" class="btn btn-secondary me-2">
                                        <i class="ri-arrow-left-line"></i> Back
                                    </a>
                                    <a href="new_consultation.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-success">
                                        <i class="ri-stethoscope-line"></i> New Consultation
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Header -->
                    <div class="patient-header">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <?php
                                $initials = '';
                                $names = explode(' ', $patient['full_name']);
                                foreach ($names as $name) {
                                    $initials .= strtoupper(substr($name, 0, 1));
                                }
                                ?>
                                <div class="patient-avatar-xl"><?php echo $initials; ?></div>
                            </div>
                            <div class="col">
                                <h3 class="text-white mb-1"><?php echo htmlspecialchars($patient['full_name']); ?></h3>
                                <p class="text-white-50 mb-2">
                                    <strong>Patient ID:</strong> <?php echo $patient['patient_number']; ?> | 
                                    <strong>Age:</strong> <?php echo $age; ?> years | 
                                    <strong>Gender:</strong> <?php echo $patient['gender']; ?> | 
                                    <strong>Blood Group:</strong> <?php echo $patient['blood_group'] ?? 'N/A'; ?>
                                </p>
                                <div>
                                    <i class="ri-phone-line me-1"></i><?php echo $patient['phone_primary']; ?>
                                    <?php if ($patient['email']): ?>
                                        <i class="ri-mail-line ms-3 me-1"></i><?php echo $patient['email']; ?>
<?php endif; ?>
</div>
</div>
<div class="col-auto">
<div class="text-end">
<h5 class="text-white"><?php echo $stats['total_consultations']; ?></h5>
<p class="text-white-50 mb-0">Total Visits</p>
</div>
</div>
</div>
</div>
<div class="row">
                    <!-- Left Column -->
                    <div class="col-lg-4">
                        <!-- Patient Information -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Personal Information</h5>
                            </div>
                            <div class="card-body">
                                <table class="table table-borderless mb-0">
                                    <tbody>
                                        <tr>
                                            <td class="text-muted">National ID:</td>
                                            <td class="fw-medium"><?php echo $patient['national_id'] ?? 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Date of Birth:</td>
                                            <td class="fw-medium"><?php echo !empty($patient['date_of_birth']) ? date('d M Y', strtotime($patient['date_of_birth'])) : 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Marital Status:</td>
                                            <td class="fw-medium"><?php echo $patient['marital_status'] ?? 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Occupation:</td>
                                            <td class="fw-medium"><?php echo $patient['occupation'] ?? 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Address:</td>
                                            <td class="fw-medium"><?php echo $patient['address'] ?? 'N/A'; ?></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Emergency Contact -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Emergency Contact</h5>
                            </div>
                            <div class="card-body">
                                <table class="table table-borderless mb-0">
                                    <tbody>
                                        <tr>
                                            <td class="text-muted">Name:</td>
                                            <td class="fw-medium"><?php echo $patient['emergency_contact_name'] ?? 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Relationship:</td>
                                            <td class="fw-medium"><?php echo $patient['emergency_contact_relationship'] ?? 'N/A'; ?></td>
                                        </tr>
                                        <tr>
                                            <td class="text-muted">Phone:</td>
                                            <td class="fw-medium"><?php echo $patient['emergency_contact_phone'] ?? 'N/A'; ?></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Allergies -->
                        <div class="card">
                            <div class="card-header bg-warning-subtle">
                                <h5 class="card-title mb-0">
                                    <i class="ri-alert-line me-2"></i>Allergies & Warnings
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($patient['allergies'])): ?>
                                    <div class="allergy-badge">
                                        <i class="ri-medicine-bottle-line me-2"></i>
                                        <?php echo htmlspecialchars($patient['allergies']); ?>
                                    </div>
                                <?php else: ?>
                                    <p class="text-muted mb-0">No known allergies</p>
                                <?php endif; ?>
                                
                                <?php if (!empty($patient['chronic_conditions'])): ?>
                                    <h6 class="mt-3 mb-2">Chronic Conditions:</h6>
                                    <p><?php echo htmlspecialchars($patient['chronic_conditions']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Insurance Information -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Insurance Information</h5>
                            </div>
                            <div class="card-body">
                                <?php
                                $insurance_query = "SELECT ip.provider_name, pi.policy_number, pi.coverage_type, pi.expiry_date, pi.status
                                                   FROM patient_insurance pi
                                                   INNER JOIN insurance_providers ip ON pi.insurance_provider_id = ip.insurance_provider_id
                                                   WHERE pi.patient_id = ? AND pi.status = 'ACTIVE'";
                                $ins_stmt = $conn->prepare($insurance_query);
                                $ins_stmt->bind_param("i", $patient_id);
                                $ins_stmt->execute();
                                $insurance = $ins_stmt->get_result()->fetch_assoc();
                                
                                if ($insurance): ?>
                                    <table class="table table-borderless mb-0">
                                        <tbody>
                                            <tr>
                                                <td class="text-muted">Provider:</td>
                                                <td class="fw-medium"><?php echo $insurance['provider_name']; ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Policy Number:</td>
                                                <td class="fw-medium"><?php echo $insurance['policy_number']; ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Coverage:</td>
                                                <td class="fw-medium"><?php echo $insurance['coverage_type']; ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted">Expiry:</td>
                                                <td class="fw-medium"><?php echo date('d M Y', strtotime($insurance['expiry_date'])); ?></td>
                                            </tr>
                                        </tbody>
                                    </table>
                                <?php else: ?>
                                    <p class="text-muted mb-0">No active insurance</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Right Column -->
                    <div class="col-lg-8">
                        <!-- Tabs -->
                        <div class="card">
                            <div class="card-body">
                                <ul class="nav nav-tabs nav-tabs-custom nav-success mb-3" role="tablist">
                                    <li class="nav-item">
                                        <a class="nav-link active" data-bs-toggle="tab" href="#consultations" role="tab">
                                            <i class="ri-stethoscope-line me-1"></i>Consultations
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="tab" href="#procedures" role="tab">
                                            <i class="ri-surgical-mask-line me-1"></i>Procedures
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="tab" href="#prescriptions" role="tab">
                                            <i class="ri-medicine-bottle-line me-1"></i>Prescriptions
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="tab" href="#labTests" role="tab">
                                            <i class="ri-flask-line me-1"></i>Lab Tests
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" data-bs-toggle="tab" href="#documents" role="tab">
                                            <i class="ri-file-text-line me-1"></i>Documents
                                        </a>
                                    </li>
                                </ul>

                                <div class="tab-content">
                                    <!-- Consultations Tab -->
                                    <div class="tab-pane active" id="consultations" role="tabpanel">
                                        <div class="timeline">
                                            <?php
                                            $consult_query = "SELECT 
                                                c.*,
                                                u.full_name as doctor_name,
                                                d.specialization
                                            FROM consultations c
                                            INNER JOIN doctors d ON c.doctor_id = d.doctor_id
                                            INNER JOIN users u ON d.user_id = u.user_id
                                            WHERE c.patient_id = ?
                                            ORDER BY c.started_at DESC, c.created_at DESC
                                            LIMIT 20";
                                            
                                            $consult_stmt = $conn->prepare($consult_query);
                                            $consult_stmt->bind_param("i", $patient_id);
                                            $consult_stmt->execute();
                                            $consultations = $consult_stmt->get_result();
                                            
                                            if ($consultations->num_rows > 0):
                                                while ($consultation = $consultations->fetch_assoc()): ?>
                                                    <div class="timeline-item">
                                                        <div class="timeline-marker"></div>
                                                        <div class="timeline-content">
                                                            <div class="card mb-2">
                                                                <div class="card-body">
                                                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                                                        <div>
                                                                            <h6 class="mb-1"><?php echo !empty($consultation['started_at']) ? date('d M Y', strtotime($consultation['started_at'])) : 'N/A'; ?></h6>
                                                                            <p class="text-muted mb-0">
                                                                                <small>Dr. <?php echo htmlspecialchars($consultation['doctor_name']); ?> 
                                                                                (<?php echo $consultation['specialization']; ?>)</small>
                                                                            </p>
                                                                        </div>
                                                                        <span class="badge badge-soft-success"><?php echo $consultation['consultation_type']; ?></span>
                                                                    </div>
                                                                    
                                                                    <?php if ($consultation['chief_complaint']): ?>
                                                                        <p class="mb-2"><strong>Chief Complaint:</strong> <?php echo htmlspecialchars($consultation['chief_complaint']); ?></p>
                                                                    <?php endif; ?>
                                                                    
                                                                    <?php if ($consultation['diagnosis_primary']): ?>
                                                                        <p class="mb-2"><strong>Diagnosis:</strong> <?php echo htmlspecialchars($consultation['diagnosis_primary']); ?></p>
                                                                    <?php endif; ?>
                                                                    
                                                                    <?php if ($consultation['treatment_plan']): ?>
                                                                        <p class="mb-2"><strong>Treatment:</strong> <?php echo htmlspecialchars(substr($consultation['treatment_plan'], 0, 150)); ?>...</p>
                                                                    <?php endif; ?>
                                                                    
                                                                    <div class="mt-3">
                                                                        <button class="btn btn-sm btn-soft-primary view-consultation-details" 
                                                                                data-id="<?php echo $consultation['consultation_id']; ?>">
                                                                            <i class="ri-eye-line me-1"></i>View Full Details
                                                                        </button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                <?php endwhile;
                                            else: ?>
                                                <div class="text-center text-muted py-4">
                                                    <i class="ri-stethoscope-line" style="font-size: 3rem;"></i>
                                                    <p class="mt-2">No consultation history available</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <!-- Procedures Tab -->
                                    <div class="tab-pane" id="procedures" role="tabpanel">
                                        <div id="proceduresContent">
                                            <div class="text-center py-4">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Prescriptions Tab -->
                                    <div class="tab-pane" id="prescriptions" role="tabpanel">
                                        <div id="prescriptionsContent">
                                            <div class="text-center py-4">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Lab Tests Tab -->
                                    <div class="tab-pane" id="labTests" role="tabpanel">
                                        <div id="labTestsContent">
                                            <div class="text-center py-4">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Documents Tab -->
                                    <div class="tab-pane" id="documents" role="tabpanel">
                                        <div id="documentsContent">
                                            <div class="text-center py-4">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">Loading...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include 'layouts/footer.php'; ?>
    </div>
</div>

<!-- Consultation Details Modal -->
<div class="modal fade" id="consultationModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Consultation Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="consultationModalBody">
                <!-- Content loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="assets/js/app.js"></script>

<script>
    $(document).ready(function() {
        var patientId = <?php echo $patient_id; ?>;
        
        // Load procedures when tab is clicked
        $('a[href="#procedures"]').on('shown.bs.tab', function() {
            if ($('#proceduresContent').html().includes('spinner-border')) {
                loadProcedures();
            }
        });
        
        // Load prescriptions when tab is clicked
        $('a[href="#prescriptions"]').on('shown.bs.tab', function() {
            if ($('#prescriptionsContent').html().includes('spinner-border')) {
                loadPrescriptions();
            }
        });
        
        // Load lab tests when tab is clicked
        $('a[href="#labTests"]').on('shown.bs.tab', function() {
            if ($('#labTestsContent').html().includes('spinner-border')) {
                loadLabTests();
            }
        });
        
        // Load documents when tab is clicked
        $('a[href="#documents"]').on('shown.bs.tab', function() {
            if ($('#documentsContent').html().includes('spinner-border')) {
                loadDocuments();
            }
        });
        
        // View consultation details
        $(document).on('click', '.view-consultation-details', function() {
            var consultationId = $(this).data('id');
            $('#consultationModalBody').html('<div class="text-center py-4"><div class="spinner-border text-primary"></div></div>');
            $('#consultationModal').modal('show');
            
            $.ajax({
                url: 'ajax/get_consultation_details.php',
                type: 'POST',
                data: { consultation_id: consultationId },
                success: function(response) {
                    $('#consultationModalBody').html(response);
                }
            });
        });
        
        function loadProcedures() {
            $.ajax({
                url: 'ajax/get_patient_procedures.php',
                type: 'POST',
                data: { patient_id: patientId },
                success: function(response) {
                    $('#proceduresContent').html(response);
                }
            });
        }
        
        function loadPrescriptions() {
            $.ajax({
                url: 'ajax/get_patient_prescriptions.php',
                type: 'POST',
                data: { patient_id: patientId },
                success: function(response) {
                    $('#prescriptionsContent').html(response);
                }
            });
        }
        
        function loadLabTests() {
            $.ajax({
                url: 'ajax/get_patient_lab_tests.php',
                type: 'POST',
                data: { patient_id: patientId },
                success: function(response) {
                    $('#labTestsContent').html(response);
                }
            });
        }
        
        function loadDocuments() {
            $.ajax({
                url: 'ajax/get_patient_documents.php',
                type: 'POST',
                data: { patient_id: patientId },
                success: function(response) {
                    $('#documentsContent').html(response);
                }
            });
        }
    });
</script>
</body>
</html>