<?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 requisition approval/rejection
if (isset($_POST['approve_requisition'])) {
    $req_id = (int)$_POST['requisition_id'];
    $approve_sql = "UPDATE pharmacy_requisitions 
                    SET status = 'APPROVED', 
                        approved_by = ?,
                        approval_date = NOW()
                    WHERE requisition_id = ?";
    $stmt = $conn->prepare($approve_sql);
    $stmt->bind_param('ii', $_SESSION['user_id'], $req_id);
    $stmt->execute();
    header('Location: pharmacy_requisitions.php?msg=approved');
    exit();
}

if (isset($_POST['reject_requisition'])) {
    $req_id = (int)$_POST['requisition_id'];
    $reason = $_POST['rejection_reason'];
    $reject_sql = "UPDATE pharmacy_requisitions 
                   SET status = 'REJECTED',
                       approved_by = ?,
                       approval_date = NOW(),
                       rejection_reason = ?
                   WHERE requisition_id = ?";
    $stmt = $conn->prepare($reject_sql);
    $stmt->bind_param('isi', $_SESSION['user_id'], $reason, $req_id);
    $stmt->execute();
    header('Location: pharmacy_requisitions.php?msg=rejected');
    exit();
}

// Filters
$filter_status = isset($_GET['status']) ? $_GET['status'] : 'PENDING';
$filter_department = isset($_GET['department']) ? $_GET['department'] : '';

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

$where_sql = count($where_clauses) > 0 ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Get requisitions
$requisitions_sql = "SELECT 
                        pr.requisition_id, pr.requisition_number, pr.department,
                        pr.priority, pr.request_date, pr.required_date,
                        pr.approval_date, pr.status, pr.total_items,
                        pr.fulfilled_items, pr.notes,
                        req_user.full_name as requested_by_name,
                        app_user.full_name as approved_by_name
                     FROM pharmacy_requisitions pr
                     INNER JOIN users req_user ON pr.requested_by = req_user.user_id
                     LEFT JOIN users app_user ON pr.approved_by = app_user.user_id
                     $where_sql
                     ORDER BY pr.request_date DESC";
$requisitions = $conn->query($requisitions_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_pending,
                SUM(CASE WHEN priority = 'URGENT' THEN 1 ELSE 0 END) as urgent_count,
                SUM(CASE WHEN priority = 'EMERGENCY' THEN 1 ELSE 0 END) as emergency_count
              FROM pharmacy_requisitions
              WHERE status = 'PENDING'";
$stats = $conn->query($stats_sql)->fetch_assoc();

// Get departments for filter
$departments_sql = "SELECT DISTINCT department FROM pharmacy_requisitions ORDER BY department";
$departments = $conn->query($departments_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pharmacy Requisitions')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .requisition-card {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            background: white;
        }
        .requisition-card.emergency {
            border-left: 4px solid #dc2626;
        }
        .requisition-card.urgent {
            border-left: 4px solid #f59e0b;
        }
    </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">Pharmacy Requisitions</h4>
                                <div class="page-title-right">
                                    <a href="pharmacy_requisition_create.php" class="btn btn-primary">
                                        <i class="ri-add-line me-1"></i>New Requisition
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-4 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-muted mb-2">Pending Requisitions</p>
                                            <h4 class="mb-0"><?php echo $stats['total_pending']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-primary rounded fs-3">
                                                <i class="ri-file-list-line text-primary"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4 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-muted mb-2">Emergency</p>
                                            <h4 class="mb-0"><?php echo $stats['emergency_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger rounded fs-3">
                                                <i class="ri-alarm-warning-line text-danger"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-4 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-muted mb-2">Urgent</p>
                                            <h4 class="mb-0"><?php echo $stats['urgent_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="ri-time-line text-warning"></i>
                                            </span>
                                        </div>
                                    </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-5">
                                            <label class="form-label">Status</label>
                                            <select class="form-control" name="status">
                                                <option value="">All Statuses</option>
                                                <option value="PENDING" <?php echo $filter_status == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="APPROVED" <?php echo $filter_status == 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                                <option value="FULFILLED" <?php echo $filter_status == 'FULFILLED' ? 'selected' : ''; ?>>Fulfilled</option>
                                                <option value="REJECTED" <?php echo $filter_status == 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                            </select>
                                        </div>
                                        <div class="col-md-5">
                                            <label class="form-label">Department</label>
                                            <select class="form-control" name="department">
                                                <option value="">All Departments</option>
                                                <?php while ($dept = $departments->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($dept['department']); ?>" 
                                                            <?php echo $filter_department == $dept['department'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($dept['department']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2 d-flex align-items-end">
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-filter-line me-1"></i>Filter
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Requisitions List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($requisitions->num_rows > 0): ?>
                                <?php while ($req = $requisitions->fetch_assoc()): ?>
                                    <div class="requisition-card <?php echo strtolower($req['priority']); ?>">
                                        <div class="row align-items-center">
                                            <div class="col-md-3">
                                                <h6 class="mb-1">
                                                    <i class="ri-file-text-line me-1"></i>
                                                    <?php echo htmlspecialchars($req['requisition_number']); ?>
                                                </h6>
                                                <p class="text-muted mb-0">
                                                    <small><?php echo date('d M Y', strtotime($req['request_date'])); ?></small>
                                                </p>
                                                <?php 
                                                $badge_class = 'badge-primary';
                                                if ($req['priority'] == 'EMERGENCY') $badge_class = 'badge-danger';
                                                elseif ($req['priority'] == 'URGENT') $badge_class = 'badge-warning';
                                                ?>
                                                <span class="badge <?php echo $badge_class; ?>">
                                                    <?php echo $req['priority']; ?>
                                                </span>
                                            </div>
                                            <div class="col-md-3">
                                                <p class="mb-1"><strong>Department:</strong></p>
                                                <p class="text-muted mb-0"><?php echo htmlspecialchars($req['department']); ?></p>
                                                <p class="mb-0"><small>By: <?php echo htmlspecialchars($req['requested_by_name']); ?></small></p>
                                            </div>
                                            <div class="col-md-2">
                                                <p class="mb-1"><strong>Items:</strong></p>
                                                <p class="mb-0"><?php echo $req['fulfilled_items']; ?> / <?php echo $req['total_items']; ?></p>
                                            </div>
                                            <div class="col-md-2">
                                                <?php
                                                $status_badge = 'badge-primary';
                                                if ($req['status'] == 'APPROVED') $status_badge = 'badge-success';
                                                elseif ($req['status'] == 'REJECTED') $status_badge = 'badge-danger';
                                                elseif ($req['status'] == 'FULFILLED') $status_badge = 'badge-info';
                                                ?>
                                                <span class="badge <?php echo $status_badge; ?>">
                                                    <?php echo str_replace('_', ' ', $req['status']); ?>
                                                </span>
                                            </div>
                                            <div class="col-md-2 text-end">
                                                <?php if ($req['status'] == 'PENDING' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST'])): ?>
                                                    <button class="btn btn-sm btn-success mb-1 w-100" 
                                                            onclick="approveRequisition(<?php echo $req['requisition_id']; ?>)">
                                                        <i class="ri-check-line me-1"></i>Approve
                                                    </button>
                                                    <button class="btn btn-sm btn-soft-danger w-100" 
                                                            onclick="rejectRequisition(<?php echo $req['requisition_id']; ?>)">
                                                        <i class="ri-close-line me-1"></i>Reject
                                                    </button>
                                                <?php else: ?>
                                                    <a href="pharmacy_requisition_view.php?id=<?php echo $req['requisition_id']; ?>" 
                                                       class="btn btn-sm btn-soft-primary w-100">
                                                        <i class="ri-eye-line me-1"></i>View
                                                    </a>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="card">
                                    <div class="card-body 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 requisitions found</h5>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </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>
    
    <script>
    function approveRequisition(reqId) {
        Swal.fire({
            title: 'Approve Requisition?',
            text: 'This will approve the requisition for fulfillment',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#10b981',
            confirmButtonText: 'Yes, approve'
        }).then((result) => {
            if (result.isConfirmed) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="requisition_id" value="${reqId}">
                    <input type="hidden" name="approve_requisition" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        });
    }

    function rejectRequisition(reqId) {
        Swal.fire({
            title: 'Reject Requisition',
            input: 'textarea',
            inputLabel: 'Rejection Reason',
            inputPlaceholder: 'Enter reason for rejection...',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            confirmButtonText: 'Reject',
            inputValidator: (value) => {
                if (!value) {
                    return 'Please provide a reason for rejection';
                }
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="requisition_id" value="${reqId}">
                    <input type="hidden" name="rejection_reason" value="${result.value}">
                    <input type="hidden" name="reject_requisition" value="1">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        });
    }
    </script>
</body>
</html>