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

// Filters
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-d', strtotime('-30 days'));
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$filter_patient_type = isset($_GET['patient_type']) ? $_GET['patient_type'] : '';
$filter_payment_status = isset($_GET['payment_status']) ? $_GET['payment_status'] : '';
$search_term = isset($_GET['search']) ? $_GET['search'] : '';

// Build query
$where_clauses = [];
$where_clauses[] = "DATE(pd.dispensing_date) BETWEEN '" . $conn->real_escape_string($filter_date_from) . "' AND '" . $conn->real_escape_string($filter_date_to) . "'";

if ($filter_patient_type) {
    $where_clauses[] = "pd.patient_type = '" . $conn->real_escape_string($filter_patient_type) . "'";
}

if ($filter_payment_status) {
    $where_clauses[] = "pd.payment_status = '" . $conn->real_escape_string($filter_payment_status) . "'";
}

if ($search_term) {
    $search_term = $conn->real_escape_string($search_term);
    $where_clauses[] = "(pd.dispensing_number LIKE '%$search_term%' OR pd.patient_name LIKE '%$search_term%' OR pd.patient_phone LIKE '%$search_term%')";
}

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

// Get dispensing history
$dispensing_sql = "SELECT 
                    pd.dispensing_id, pd.dispensing_number, pd.patient_name,
                    pd.patient_type, pd.patient_phone, pd.dispensing_date,
                    pd.total_amount, pd.amount_paid, pd.balance,
                    pd.payment_method, pd.payment_status,
                    u.full_name as pharmacist_name,
                    (SELECT COUNT(*) FROM pharmacy_dispensing_items pdi 
                     WHERE pdi.dispensing_id = pd.dispensing_id) as item_count
                   FROM pharmacy_dispensing pd
                   INNER JOIN users u ON pd.dispensed_by = u.user_id
                   WHERE $where_sql
                   ORDER BY pd.dispensing_date DESC";
$dispensing_records = $conn->query($dispensing_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_records,
                SUM(total_amount) as total_sales,
                SUM(amount_paid) as total_collected,
                SUM(balance) as total_balance,
                COUNT(CASE WHEN payment_status = 'PAID' THEN 1 END) as fully_paid_count
              FROM pharmacy_dispensing
              WHERE DATE(dispensing_date) BETWEEN ? AND ?";
$stmt = $conn->prepare($stats_sql);
$stmt->bind_param('ss', $filter_date_from, $filter_date_to);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Dispensing History')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.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;
        }
    </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">Dispensing History</h4>
                                <div class="page-title-right">
                                    <button class="btn btn-success" onclick="exportHistory()">
                                        <i class="ri-file-excel-line me-1"></i>Export
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #3b82f6;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Total Records</p>
                                        <h4 class="mb-0"><?php echo number_format($stats['total_records']); ?></h4>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-primary rounded-circle fs-3">
                                            <i class="ri-file-list-line text-primary"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #10b981;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Total Sales</p>
                                        <h4 class="mb-0">KES <?php echo number_format($stats['total_sales'], 0); ?></h4>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                            <i class="ri-money-dollar-circle-line text-success"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #06b6d4;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Collected</p>
                                        <h4 class="mb-0">KES <?php echo number_format($stats['total_collected'], 0); ?></h4>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-soft-info rounded-circle fs-3">
                                            <i class="ri-hand-coin-line text-info"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #f59e0b;">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <p class="text-muted mb-1">Balance</p>
                                        <h4 class="mb-0">KES <?php echo number_format($stats['total_balance'], 0); ?></h4>
                                    </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>

                    <!-- 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-2">
                                            <label class="form-label">From Date</label>
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo $filter_date_from; ?>" required>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">To Date</label>
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo $filter_date_to; ?>" required>
                                        </div>
                                        <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="Dispensing #, patient...">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Patient Type</label>
                                            <select class="form-control" name="patient_type">
                                                <option value="">All Types</option>
                                                <option value="REGISTERED" <?php echo $filter_patient_type == 'REGISTERED' ? 'selected' : ''; ?>>Registered</option>
                                                <option value="WALK_IN" <?php echo $filter_patient_type == 'WALK_IN' ? 'selected' : ''; ?>>Walk-In</option>
                                                <option value="REFERRED" <?php echo $filter_patient_type == 'REFERRED' ? 'selected' : ''; ?>>Referred</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Payment Status</label>
                                            <select class="form-control" name="payment_status">
                                                <option value="">All Status</option>
                                                <option value="PAID" <?php echo $filter_payment_status == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                                <option value="PARTIAL" <?php echo $filter_payment_status == 'PARTIAL' ? 'selected' : ''; ?>>Partial</option>
                                                <option value="PENDING" <?php echo $filter_payment_status == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                            </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>

                    <!-- History Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="historyTable" class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Dispensing #</th>
                                                    <th>Date & Time</th>
                                                    <th>Patient</th>
                                                    <th>Type</th>
                                                    <th>Items</th>
                                                    <th>Amount</th>
                                                    <th>Paid</th>
                                                    <th>Balance</th>
                                                    <th>Payment</th>
                                                    <th>Status</th>
                                                    <th>Pharmacist</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($record = $dispensing_records->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><strong><?php echo htmlspecialchars($record['dispensing_number']); ?></strong></td>
                                                        <td><?php echo date('d M Y, h:i A', strtotime($record['dispensing_date'])); ?></td>
                                                        <td>
                                                            <?php echo htmlspecialchars($record['patient_name']); ?>
                                                            <?php if ($record['patient_phone']): ?>
                                                                <br><small class="text-muted"><?php echo htmlspecialchars($record['patient_phone']); ?></small>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge badge-soft-info">
                                                                <?php echo str_replace('_', ' ', $record['patient_type']); ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo $record['item_count']; ?></td>
                                                        <td>KES <?php echo number_format($record['total_amount'], 2); ?></td>
                                                        <td>KES <?php echo number_format($record['amount_paid'], 2); ?></td>
                                                        <td>
                                                            <?php if ($record['balance'] > 0): ?>
                                                                <span class="text-danger">KES <?php echo number_format($record['balance'], 2); ?></span>
                                                            <?php else: ?>
                                                                <span class="text-muted">-</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?php echo str_replace('_', ' ', $record['payment_method']); ?></td>
                                                        <td>
                                                            <?php
                                                            $status_badge = 'badge-success';
                                                            if ($record['payment_status'] == 'PENDING') $status_badge = 'badge-warning';
                                                            elseif ($record['payment_status'] == 'PARTIAL') $status_badge = 'badge-info';
                                                            ?>
                                                            <span class="badge <?php echo $status_badge; ?>">
                                                                <?php echo $record['payment_status']; ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($record['pharmacist_name']); ?></td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-soft-secondary dropdown-toggle" 
                                                                        type="button" data-bs-toggle="dropdown">
                                                                    <i class="ri-more-2-fill"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li>
                                                                        <a class="dropdown-item" href="pharmacy_dispensing_view.php?id=<?php echo $record['dispensing_id']; ?>">
                                                                            <i class="ri-eye-line me-2"></i>View Details
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item" href="pharmacy_receipt_print.php?id=<?php echo $record['dispensing_id']; ?>" target="_blank">
                                                                            <i class="ri-printer-line me-2"></i>Print Receipt
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </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/js/app.js"></script>
    
    <script>
    $(document).ready(function() {
        $('#historyTable').DataTable({
            pageLength: 25,
            order: [[1, 'desc']]
        });
    });

    function exportHistory() {
        const params = new URLSearchParams(window.location.search);
        window.location.href = 'pharmacy_dispensing_export.php?' + params.toString();
    }
    </script>
</body>
</html>