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

$doctor_id = $_SESSION['user_id'];
$patient_id = $_GET['patient_id'] ?? 0;

// Get patient details
$patient_query = "SELECT p.*, u.full_name FROM patients p
                 INNER JOIN users u ON p.user_id = u.user_id
                 WHERE p.patient_id = ?";
$patient_stmt = $conn->prepare($patient_query);
$patient_stmt->bind_param("i", $patient_id);
$patient_stmt->execute();
$patient = $patient_stmt->get_result()->fetch_assoc();

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

// Get document statistics
$stats_query = "SELECT 
    COUNT(*) as total_documents,
    COUNT(CASE WHEN document_type = 'MEDICAL_REPORT' THEN 1 END) as reports,
    COUNT(CASE WHEN document_type = 'LAB_RESULT' THEN 1 END) as lab_results,
    COUNT(CASE WHEN document_type = 'IMAGING' THEN 1 END) as imaging
FROM medical_documents
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 Documents')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</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 Documents - <?php echo htmlspecialchars($patient['full_name']); ?></h4>
                                <div class="page-title-right">
                                    <a href="upload_document.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-success me-2">
                                        <i class="ri-upload-line me-1"></i> Upload Document
                                    </a>
                                    <a href="patient_medical_history.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line"></i> Back
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Info Bar -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card" style="background: linear-gradient(135deg, #2d7a2d, #26a69a); color: white;">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <h5 class="text-white mb-1"><?php echo htmlspecialchars($patient['full_name']); ?></h5>
                                            <p class="text-white-50 mb-0">
                                                <strong>Patient ID:</strong> <?php echo $patient['patient_number']; ?>
                                            </p>
                                        </div>
                                        <div class="col-md-4 text-end">
                                            <h6 class="text-white"><?php echo $stats['total_documents']; ?> Documents</h6>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Total Documents</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['total_documents']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="bx bx-file text-success"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Medical Reports</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['reports']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="bx bx-file-blank text-info"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Lab Results</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['lab_results']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="bx bx-test-tube text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-uppercase fw-medium text-muted mb-0">Imaging</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4"><?php echo $stats['imaging']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="bx bx-image text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Documents Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">All Documents</h5>
                                        <div>
                                            <select class="form-select form-select-sm" id="filterDocumentType" style="width: 200px;">
                                                <option value="">All Document Types</option>
                                                <option value="MEDICAL_REPORT">Medical Reports</option>
                                                <option value="LAB_RESULT">Lab Results</option>
                                                <option value="IMAGING">Imaging</option>
                                                <option value="PRESCRIPTION">Prescriptions</option>
                                                <option value="CONSENT_FORM">Consent Forms</option>
                                                <option value="OTHER">Other</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <table id="documentsTable" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Date</th>
                                                <th>Document Type</th>
                                                <th>Document Name</th>
                                                <th>Description</th>
                                                <th>Uploaded By</th>
                                                <th>File Size</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <!-- Data loaded via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- View Document Modal -->
    <div class="modal fade" id="viewDocumentModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Document Viewer</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" style="min-height: 500px;">
                    <iframe id="documentViewer" style="width: 100%; height: 600px; border: none;"></iframe>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="downloadDocument">
                        <i class="ri-download-line me-1"></i> Download
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <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; ?>;
            var currentDocumentId = null;

            var table = $('#documentsTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_patient_documents.php',
                    type: 'POST',
                    data: function(d) {
                        d.patient_id = patientId;
                        d.document_type = $('#filterDocumentType').val();
                    }
                },
                columns: [
                    { data: 'upload_date' },
                    { data: 'document_type' },
                    { data: 'document_name' },
                    { data: 'description' },
                    { data: 'uploaded_by' },
                    { data: 'file_size' },
                    { data: 'actions' }
                ],
                order: [[0, 'desc']],
                pageLength: 25
            });

            // Filter by document type
            $('#filterDocumentType').on('change', function() {
                table.ajax.reload();
            });

            // View document
            $(document).on('click', '.btn-view-document', function() {
                currentDocumentId = $(this).data('id');
                var fileUrl = $(this).data('url');
                
                $('#documentViewer').attr('src', fileUrl);
                $('#viewDocumentModal').modal('show');
            });

            // Download document
            $('#downloadDocument').on('click', function() {
                if (currentDocumentId) {
                    window.location.href = 'download_document.php?document_id=' + currentDocumentId;
                }
            });

            // Share document
            $(document).on('click', '.btn-share-document', function() {
                var documentId = $(this).data('id');
                window.location.href = 'share_medical_data.php?document_id=' + documentId + '&patient_id=' + patientId;
            });

            // Delete document
            $(document).on('click', '.btn-delete-document', function() {
                var documentId = $(this).data('id');
                
                Swal.fire({
                    title: 'Delete Document',
                    text: 'Are you sure you want to delete this document? This action cannot be undone.',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Delete',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#d33'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: 'ajax/delete_patient_document.php',
                            type: 'POST',
                            data: { document_id: documentId },
                            success: function(response) {
                                var result = JSON.parse(response);
                                if (result.success) {
                                    Swal.fire('Deleted!', 'Document has been deleted', 'success');
                                    table.ajax.reload();
                                } else {
                                    Swal.fire('Error!', result.message, 'error');
                                }
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>