<?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'];

// Get statistics
$stats_query = "SELECT 
    COUNT(*) as total_procedures,
    COUNT(CASE WHEN procedure_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as last_30_days,
    COUNT(CASE WHEN procedure_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 1 END) as last_7_days,
    COUNT(DISTINCT patient_id) as unique_patients
FROM procedures
WHERE doctor_id = ? AND procedure_status = 'COMPLETED'";

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

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Procedure History')); ?>
    <?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">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css" />
</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">Procedure History</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="ent_consultant_dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Procedure History</li>
                                    </ol>
                                </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 Procedures</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 number_format($stats['total_procedures']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-success rounded fs-3">
                                                <i class="bx bx-plus-medical 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">Unique Patients</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 number_format($stats['unique_patients']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-info rounded fs-3">
                                                <i class="bx bx-user-circle 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">Last 7 Days</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 number_format($stats['last_7_days']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="bx bx-calendar-week 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">Last 30 Days</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 number_format($stats['last_30_days']); ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="bx bx-calendar text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="row align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label">Date Range</label>
                                            <input type="text" class="form-control" id="dateRange" placeholder="Select date range">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Patient Name</label>
                                            <input type="text" class="form-control" id="filterPatient" placeholder="Search patient...">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Procedure Type</label>
                                            <select class="form-select" id="filterType">
                                                <option value="">All Types</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <button class="btn btn-primary w-100" id="applyFilter">
                                                <i class="ri-filter-line me-1"></i> Filter
                                            </button>
                                        </div>
                                        <div class="col-md-2">
                                            <button class="btn btn-soft-secondary w-100" id="resetFilter">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- History 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">Completed Procedures</h5>
                                        <button class="btn btn-soft-success" id="exportBtn">
                                            <i class="ri-file-excel-line"></i> Export
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <table id="historyTable" class="table table-bordered dt-responsive nowrap table-striped align-middle" style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Procedure ID</th>
                                                <th>Date</th>
                                                <th>Patient</th>
                                                <th>Procedure Type</th>
                                                <th>Duration</th>
                                                <th>Outcome</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 Procedure Modal -->
    <div class="modal fade" id="viewModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Procedure Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="modalBody">
                    <!-- Content loaded via AJAX -->
                </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="printProcedure">
                        <i class="ri-printer-line me-1"></i> Print
                    </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/libs/flatpickr/flatpickr.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            flatpickr("#dateRange", {
                mode: "range",
                dateFormat: "Y-m-d"
            });

            $.ajax({
                url: 'ajax/get_procedure_types.php',
                type: 'POST',
                success: function(response) {
                    var types = JSON.parse(response);
                    types.forEach(function(type) {
                        $('#filterType').append('<option value="' + type.procedure_type_id + '">' + type.procedure_name + '</option>');
                    });
                }
            });

            var table = $('#historyTable').DataTable({
                processing: true,
                serverSide: false,
                ajax: {
                    url: 'ajax/get_procedure_history.php',
                    type: 'POST',
                    data: function(d) {
                        d.date_range = $('#dateRange').val();
                        d.patient = $('#filterPatient').val();
                        d.type = $('#filterType').val();
                    }
                },
                columns: [
                    { data: 'procedure_id' },
                    { data: 'procedure_date' },
                    { data: 'patient_name' },
                    { data: 'procedure_type' },
                    { data: 'duration' },
                    { data: 'outcome' },
                    { data: 'actions' }
                ],
                order: [[1, 'desc']],
                pageLength: 25
            });

            $('#applyFilter').on('click', function() {
                table.ajax.reload();
            });

            $('#resetFilter').on('click', function() {
                $('#dateRange, #filterPatient, #filterType').val('');
                table.ajax.reload();
            });

            $(document).on('click', '.btn-view', function() {
                var procedureId = $(this).data('id');
                $('#modalBody').html('<div class="text-center py-5"><div class="spinner-border text-primary"></div></div>');
                $('#viewModal').modal('show');
                
                $.ajax({
                    url: 'ajax/get_procedure_details.php',
                    type: 'POST',
                    data: { procedure_id: procedureId },
                    success: function(response) {
                        $('#modalBody').html(response);
                    }
                });
            });

            $('#exportBtn').on('click', function() {
                var dateRange = $('#dateRange').val();
                var patient = $('#filterPatient').val();
                var type = $('#filterType').val();
                
                window.location.href = 'export/export_procedure_history.php?date_range=' + dateRange + '&patient=' + patient + '&type=' + type;
            });

            $('#printProcedure').on('click', function() {
                var printContent = $('#modalBody').html();
                var printWindow = window.open('', '', 'height=600,width=800');
                printWindow.document.write('<html><head><title>Procedure Details</title>');
                printWindow.document.write('<link href="assets/css/bootstrap.min.css" rel="stylesheet">');
                printWindow.document.write('</head><body>');
                printWindow.document.write(printContent);
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                printWindow.print();
            });
        });
    </script>
</body>
</html>