<?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', 'CHIEF_PHARMACIST', 'PHARMACIST', 'PHARMACY_TECH'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Handle filters
$filter_status = isset($_GET['status']) ? $_GET['status'] : 'ACTIVE';
$filter_date = isset($_GET['date']) ? $_GET['date'] : '';
$filter_doctor = isset($_GET['doctor']) ? $_GET['doctor'] : '';
$search_term = isset($_GET['search']) ? $_GET['search'] : '';

// Build query
$where_clauses = ["p.dispensed = 0"];

if ($filter_status) {
    $where_clauses[] = "p.status = '" . $conn->real_escape_string($filter_status) . "'";
}

if ($filter_date) {
    $where_clauses[] = "DATE(p.prescribed_date) = '" . $conn->real_escape_string($filter_date) . "'";
}

if ($filter_doctor) {
    $where_clauses[] = "p.doctor_id = " . (int)$filter_doctor;
}

if ($search_term) {
    $search_term = $conn->real_escape_string($search_term);
    $where_clauses[] = "(u.full_name LIKE '%$search_term%' OR p.prescription_number LIKE '%$search_term%' OR p.medication_name LIKE '%$search_term%' OR pt.patient_number LIKE '%$search_term%')";
}

$where_sql = implode(' AND ', $where_clauses);

// Get prescriptions
$prescriptions_sql = "SELECT 
                        p.prescription_id, p.prescription_number, p.medication_name,
                        p.dosage, p.frequency, p.duration, p.quantity,
                        p.prescribed_date, p.status, p.instructions,
                        pt.patient_number, u.full_name as patient_name,
                        u.phone_primary as patient_phone,
                        doc.full_name as doctor_name,
                        pv.visit_number,
                        DATEDIFF(CURDATE(), p.prescribed_date) as days_pending
                      FROM prescriptions p
                      INNER JOIN patients pt ON p.patient_id = pt.patient_id
                      INNER JOIN users u ON pt.user_id = u.user_id
                      INNER JOIN users doc ON p.doctor_id = doc.user_id
                      LEFT JOIN patient_visits pv ON p.visit_id = pv.visit_id
                      WHERE $where_sql
                      ORDER BY p.prescribed_date DESC";
$prescriptions = $conn->query($prescriptions_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_pending,
                COUNT(CASE WHEN DATEDIFF(CURDATE(), prescribed_date) > 3 THEN 1 END) as overdue,
                COUNT(CASE WHEN DATE(prescribed_date) = CURDATE() THEN 1 END) as today
              FROM prescriptions
              WHERE dispensed = 0 AND status = 'ACTIVE'";
$stats = $conn->query($stats_sql)->fetch_assoc();

// Get doctors for filter
$doctors_sql = "SELECT DISTINCT u.user_id, u.full_name 
                FROM users u
                INNER JOIN user_roles ur ON u.role_id = ur.role_id
                WHERE ur.role_code IN ('ENT_DOCTOR', 'ENT_CONSULTANT')
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pending Prescriptions')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid;
        }
        .stat-card.primary { border-left-color: #3b82f6; }
        .stat-card.warning { border-left-color: #f59e0b; }
        .stat-card.success { border-left-color: #10b981; }
        
        .prescription-card {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: white;
            transition: all 0.2s;
        }
        .prescription-card:hover {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .overdue {
            border-left: 4px solid #ef4444;
        }
    </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">Pending Prescriptions</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="pharmacy_dashboard.php">Pharmacy</a></li>
                                        <li class="breadcrumb-item active">Prescriptions</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="stat-card primary">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Total Pending</p>
                                        <h3 class="mb-0"><?php echo $stats['total_pending']; ?></h3>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-primary rounded-circle fs-3">
                                            <i class="ri-file-list-3-line text-primary"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card warning">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Overdue (>3 days)</p>
                                        <h3 class="mb-0"><?php echo $stats['overdue']; ?></h3>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-warning rounded-circle fs-3">
                                            <i class="ri-alarm-warning-line text-warning"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card success">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Today's Prescriptions</p>
                                        <h3 class="mb-0"><?php echo $stats['today']; ?></h3>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                            <i class="ri-calendar-check-line text-success"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" action="" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search_term); ?>"
                                                   placeholder="Patient name, prescription #...">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Status</label>
                                            <select class="form-control" name="status">
                                                <option value="">All Statuses</option>
                                                <option value="ACTIVE" <?php echo $filter_status == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="COMPLETED" <?php echo $filter_status == 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Date</label>
                                            <input type="date" class="form-control" name="date" value="<?php echo $filter_date; ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Doctor</label>
                                            <select class="form-control" name="doctor">
                                                <option value="">All Doctors</option>
                                                <?php while ($doc = $doctors->fetch_assoc()): ?>
                                                    <option value="<?php echo $doc['user_id']; ?>" 
                                                            <?php echo $filter_doctor == $doc['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($doc['full_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-1 d-flex align-items-end">
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-search-line"></i>
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Prescriptions List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <?php if ($prescriptions->num_rows > 0): ?>
                                        <?php while ($rx = $prescriptions->fetch_assoc()): ?>
                                            <div class="prescription-card <?php echo $rx['days_pending'] > 3 ? 'overdue' : ''; ?>">
                                                <div class="row align-items-center">
                                                    <div class="col-md-3">
                                                        <h6 class="mb-1">
                                                            <i class="ri-file-list-line me-1"></i>
                                                            <?php echo htmlspecialchars($rx['prescription_number']); ?>
                                                        </h6>
                                                        <p class="text-muted mb-0">
                                                            <small><?php echo date('d M Y', strtotime($rx['prescribed_date'])); ?></small>
                                                            <?php if ($rx['days_pending'] > 3): ?>
                                                                <span class="badge badge-soft-danger ms-2">
                                                                    <?php echo $rx['days_pending']; ?> days pending
                                                                </span>
                                                            <?php endif; ?>
                                                        </p>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <div class="d-flex align-items-center">
                                                            <div class="avatar-sm flex-shrink-0 me-2">
                                                                <span class="avatar-title bg-soft-primary rounded-circle">
                                                                    <?php echo strtoupper(substr($rx['patient_name'], 0, 2)); ?>
                                                                </span>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-0"><?php echo htmlspecialchars($rx['patient_name']); ?></h6>
                                                                <p class="text-muted mb-0"><small><?php echo htmlspecialchars($rx['patient_number']); ?></small></p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <p class="mb-1"><strong><?php echo htmlspecialchars($rx['medication_name']); ?></strong></p>
                                                        <p class="text-muted mb-0">
                                                            <small>
                                                                <?php echo htmlspecialchars($rx['dosage']); ?> | 
                                                                <?php echo htmlspecialchars($rx['frequency']); ?> | 
                                                                <?php echo htmlspecialchars($rx['duration']); ?>
                                                            </small>
                                                        </p>
                                                        <p class="text-muted mb-0"><small>Dr. <?php echo htmlspecialchars($rx['doctor_name']); ?></small></p>
                                                    </div>
                                                    <div class="col-md-2 text-end">
                                                        <a href="pharmacy_dispense.php?prescription_id=<?php echo $rx['prescription_id']; ?>" 
                                                           class="btn btn-primary btn-sm mb-1 w-100">
                                                            <i class="ri-capsule-line me-1"></i>Dispense
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-file-list-3-line text-muted" style="font-size: 4rem;"></i>
                                            <h5 class="mt-3 text-muted">No pending prescriptions</h5>
                                        </div>
                                    <?php endif; ?>
                                </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 src="assets/js/app.js"></script>
</body>
</html>