<?php
session_start();
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) { echo '<p class="text-danger">Unauthorized</p>'; exit(); }

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) { echo '<p class="text-danger">Access denied</p>'; exit(); }

$patient_id = (int)($_GET['patient_id'] ?? 0);
$date_from  = $_GET['date_from'] ?? date('Y-m-01');
$date_to    = $_GET['date_to']   ?? date('Y-m-d');

if (!$patient_id) { echo '<p class="text-danger">No patient specified.</p>'; exit(); }

$from_dt = $date_from . ' 00:00:00';
$to_dt   = date('Y-m-d', strtotime($date_to . ' +1 day')) . ' 00:00:00';

$stmt = $conn->prepare(
    "SELECT pd.dispensing_id, pd.dispensing_number, pd.dispensing_date,
            pd.total_amount, pd.payment_method, pd.payment_status, pd.is_reversed,
            u.full_name AS pharmacist,
            (SELECT GROUP_CONCAT(pdi.item_name, ' x', pdi.quantity SEPARATOR '; ')
             FROM pharmacy_dispensing_items pdi WHERE pdi.dispensing_id = pd.dispensing_id) AS items
     FROM pharmacy_dispensing pd
     JOIN users u ON pd.dispensed_by = u.user_id
     WHERE pd.patient_id = ?
       AND pd.dispensing_date >= ? AND pd.dispensing_date < ?
     ORDER BY pd.dispensing_date DESC"
);
$stmt->bind_param('iss', $patient_id, $from_dt, $to_dt);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

if (empty($rows)): ?>
<p class="text-center text-muted py-3">No dispensing records found for this patient in the selected period.</p>
<?php else: ?>
<div class="table-responsive">
    <table class="table table-sm table-hover align-middle" style="font-size:.83rem;">
        <thead class="table-light">
            <tr>
                <th>Dispensing #</th>
                <th>Date</th>
                <th>Items Dispensed</th>
                <th class="text-end">Amount (KES)</th>
                <th>Payment</th>
                <th>Status</th>
                <th>Pharmacist</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $total = 0;
            foreach ($rows as $r):
                $total += (float)$r['total_amount'];
                $ps_cls = match($r['payment_status']) {
                    'PAID'    => '#d1fae5|#065f46',
                    'PARTIAL' => '#fef3c7|#92400e',
                    'CREDIT'  => '#e0e7ff|#3730a3',
                    default   => '#f1f5f9|#475569'
                };
                [$ps_bg, $ps_fg] = explode('|', $ps_cls);
            ?>
            <tr <?php echo $r['is_reversed'] ? 'style="opacity:.55;text-decoration:line-through;"' : ''; ?>>
                <td class="fw-semibold" style="font-family:monospace;"><?php echo htmlspecialchars($r['dispensing_number']); ?></td>
                <td><?php echo date('d M Y, H:i', strtotime($r['dispensing_date'])); ?></td>
                <td style="max-width:300px; word-break:break-word;"><?php echo htmlspecialchars($r['items'] ?? '—'); ?></td>
                <td class="text-end fw-semibold" style="font-family:monospace;"><?php echo number_format((float)$r['total_amount'], 2); ?></td>
                <td><?php echo htmlspecialchars($r['payment_method']); ?></td>
                <td>
                    <span style="background:<?php echo $ps_bg; ?>;color:<?php echo $ps_fg; ?>;padding:.15rem .55rem;border-radius:20px;font-size:.7rem;font-weight:600;">
                        <?php echo $r['is_reversed'] ? 'REVERSED' : htmlspecialchars($r['payment_status']); ?>
                    </span>
                </td>
                <td class="text-muted"><?php echo htmlspecialchars($r['pharmacist']); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr class="table-light fw-semibold">
                <td colspan="3" class="text-end">Total</td>
                <td class="text-end" style="font-family:monospace;">KES <?php echo number_format($total, 2); ?></td>
                <td colspan="3"></td>
            </tr>
        </tfoot>
    </table>
</div>
<?php endif; ?>
