<?php
// delete.php - View, filter, and delete receipts with pagination (standalone)

$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "paymentpack";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4");

// ---- GET parameters ----
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$facility_filter = isset($_GET['facility']) ? trim($_GET['facility']) : '';
$per_page = 20;

// ---- Handle POST: Delete selected records ----
$message = '';
$message_type = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_ids']) && is_array($_POST['delete_ids'])) {
    $delete_ids = array_map('intval', $_POST['delete_ids']);
    if (count($delete_ids) > 0) {
        $conn->begin_transaction();
        try {
            $placeholders = implode(',', array_fill(0, count($delete_ids), '?'));
            $delete_sql = "DELETE FROM receipts WHERE id IN ($placeholders)";
            $stmt = $conn->prepare($delete_sql);
            $stmt->bind_param(str_repeat('i', count($delete_ids)), ...$delete_ids);
            $stmt->execute();
            $deleted_count = $stmt->affected_rows;
            $stmt->close();

            // Reindex
            $check_sql = "SELECT COUNT(*) as cnt FROM receipts";
            $check_result = $conn->query($check_sql);
            $row_cnt = $check_result->fetch_assoc()['cnt'];
            if ($row_cnt == 0) {
                $conn->query("ALTER TABLE receipts AUTO_INCREMENT = 1");
            } else {
                $max_sql = "SELECT MAX(id) as max_id FROM receipts";
                $max_result = $conn->query($max_sql);
                $max_id = $max_result->fetch_assoc()['max_id'] ?? 0;
                $next_id = $max_id + 1;
                $conn->query("ALTER TABLE receipts AUTO_INCREMENT = $next_id");
            }
            $conn->commit();

            // Redirect to preserve filter & page
            header("Location: delete.php?page=" . $page . "&facility=" . urlencode($facility_filter));
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $message = "Error: " . $e->getMessage();
            $message_type = 'error';
        }
    } else {
        $message = "No records selected.";
        $message_type = 'warning';
    }
}

// ---- Build WHERE clause ----
$where = "1=1";
$params = [];
$types = "";
if (!empty($facility_filter)) {
    $where .= " AND facility = ?";
    $params[] = $facility_filter;
    $types .= "s";
}

// ---- Count total ----
$count_sql = "SELECT COUNT(*) as total FROM receipts WHERE $where";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$total_records = $count_result->fetch_assoc()['total'];
$count_stmt->close();
$total_pages = ceil($total_records / $per_page);
$offset = ($page - 1) * $per_page;

// ---- Fetch records ----
$sql = "SELECT id, InvoiceNo_str, facility, district, upload_date, upload_month, uploaded_by, del_point 
        FROM receipts 
        WHERE $where 
        ORDER BY id DESC 
        LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$param_types = $types . "ii";
$params[] = $per_page;
$params[] = $offset;
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
$records = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// ---- Distinct facilities ----
$facility_list = [];
$fac_sql = "SELECT DISTINCT facility FROM receipts WHERE facility IS NOT NULL AND facility != '' ORDER BY facility";
$fac_res = $conn->query($fac_sql);
if ($fac_res) {
    while ($row = $fac_res->fetch_assoc()) {
        $facility_list[] = $row['facility'];
    }
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Receipts | KZN Health</title>
    <style>
        /* (same styles as before – kept compact) */
        * { box-sizing: border-box; margin:0; padding:0; }
        body { font-family:'Inter',sans-serif; background:#f0f4fb; padding:30px 20px; min-height:100vh; display:flex; justify-content:center; }
        .container { max-width:1200px; width:100%; background:#fff; border-radius:32px; box-shadow:0 20px 60px rgba(0,20,40,0.15); padding:32px 28px; }
        h1 { font-size:28px; font-weight:700; color:#0b1b2f; display:flex; align-items:center; gap:12px; margin-bottom:6px; }
        .sub { color:#5e6f88; font-size:14px; margin-bottom:24px; }
        .top-bar { display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:16px; margin-bottom:20px; }
        .filter-form { display:flex; flex-wrap:wrap; align-items:center; gap:10px; }
        .filter-form label { font-weight:600; color:#0b1b2f; font-size:14px; }
        .filter-form select, .filter-form input[type="submit"] { padding:8px 16px; border-radius:10px; border:1.5px solid #d0d9e6; background:#fafcff; font-size:14px; transition:border-color .2s; }
        .filter-form select:focus, .filter-form input:focus { border-color:#2a6bb0; outline:none; box-shadow:0 0 0 4px rgba(42,107,176,0.10); }
        .filter-form input[type="submit"] { background:#1a4f8a; color:#fff; border:none; font-weight:600; cursor:pointer; }
        .filter-form input[type="submit"]:hover { background:#0f3d6b; }
        .btn { display:inline-flex; align-items:center; gap:6px; padding:8px 18px; border-radius:10px; font-weight:600; font-size:14px; border:none; cursor:pointer; transition:all .2s; font-family:inherit; text-decoration:none; }
        .btn-danger { background:#c0392b; color:#fff; }
        .btn-danger:hover { background:#a93226; transform:translateY(-1px); }
        .btn-danger:disabled { opacity:0.5; cursor:not-allowed; transform:none; }
        .btn-secondary { background:#eef3fa; color:#1a2d44; }
        .btn-secondary:hover { background:#e2ecf9; }
        .btn-success { background:#1a8a4a; color:#fff; }
        .btn-success:hover { background:#12703b; }
        .btn-outline { background:transparent; color:#1a4f8a; border:1.5px solid #d0d9e6; }
        .btn-outline:hover { background:#f0f6fe; border-color:#1a4f8a; }
        .message { padding:12px 16px; border-radius:12px; font-size:14px; font-weight:500; margin-bottom:18px; }
        .message.success { background:#e6f5ed; color:#0f6e3a; border:1px solid #b8e0cc; }
        .message.error { background:#fde9e9; color:#a32d2d; border:1px solid #f5cdcd; }
        .message.warning { background:#fef7e0; color:#8a6d1b; border:1px solid #f5e3b8; }
        .table-wrap { overflow-x:auto; border-radius:16px; border:1px solid #e9eef4; margin-top:8px; }
        table { width:100%; border-collapse:collapse; font-size:14px; min-width:700px; }
        th { background:#eef3fa; color:#1a2d44; font-weight:600; padding:12px 14px; text-align:left; border-bottom:2px solid #d6e0eb; font-size:12px; text-transform:uppercase; letter-spacing:0.03em; }
        td { padding:10px 14px; border-bottom:1px solid #eef3f8; color:#1f334a; vertical-align:middle; }
        tr:hover td { background:#f8fbff; }
        .checkbox-col { width:40px; text-align:center; }
        .badge { display:inline-block; padding:2px 10px; border-radius:20px; font-size:12px; font-weight:600; background:#e6edf8; color:#1a4f8a; }
        .pagination { display:flex; justify-content:flex-end; align-items:center; gap:6px; margin-top:16px; flex-wrap:wrap; }
        .pagination a, .pagination span { padding:6px 14px; border-radius:8px; border:1px solid #d0d9e6; background:#fafcff; color:#1a4f8a; text-decoration:none; font-size:14px; font-weight:500; transition:all .2s; }
        .pagination a:hover { background:#e6edf8; border-color:#1a4f8a; }
        .pagination .current { background:#1a4f8a; color:#fff; border-color:#1a4f8a; }
        .pagination .disabled { color:#b0bed0; pointer-events:none; background:#f0f4fa; }
        .actions-bar { display:flex; gap:12px; flex-wrap:wrap; align-items:center; margin-top:14px; }
        .back-link { display:inline-block; color:#1a4f8a; text-decoration:none; font-weight:600; font-size:14px; margin-top:10px; }
        .back-link:hover { text-decoration:underline; }
        .no-data { padding:30px; text-align:center; color:#6a7f9b; font-style:italic; }
        @media (max-width:600px) { .container{ padding:20px 12px; } .top-bar{ flex-direction:column; align-items:stretch; } .filter-form{ flex-wrap:wrap; } .filter-form select,.filter-form input{ width:100%; } .actions-bar{ flex-direction:column; align-items:stretch; } .btn{ justify-content:center; } }
    </style>
</head>
<body>
<div class="container">
    <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px;">
        <div><h1>📋 Manage Receipts</h1><p class="sub">View, filter, and delete receipt records.</p></div>
        <div><a href="receipt.php" class="btn btn-secondary">⬆ Upload New</a><a href="../index.php" class="btn btn-outline">🏠 Home</a></div>
    </div>

    <?php if ($message): ?>
        <div class="message <?php echo $message_type; ?>"><?php echo htmlspecialchars($message); ?></div>
    <?php endif; ?>

    <div class="top-bar">
        <form method="get" class="filter-form">
            <label for="facility">Filter by Facility:</label>
            <select name="facility" id="facility">
                <option value="">-- All --</option>
                <?php foreach ($facility_list as $f): ?>
                    <option value="<?php echo htmlspecialchars($f); ?>" <?php echo ($facility_filter === $f) ? 'selected' : ''; ?>><?php echo htmlspecialchars($f); ?></option>
                <?php endforeach; ?>
            </select>
            <input type="submit" value="Apply Filter">
            <?php if (!empty($facility_filter)): ?>
                <a href="?facility=" class="btn btn-outline" style="padding:6px 14px;">Clear</a>
            <?php endif; ?>
        </form>
        <div>
            <span class="badge">Total: <?php echo $total_records; ?> records</span>
            <?php if (!empty($facility_filter)): ?>
                <span class="badge" style="background:#e6f5ed;color:#0f6e3a;">Filtered: <?php echo htmlspecialchars($facility_filter); ?></span>
            <?php endif; ?>
        </div>
    </div>

    <form method="post" id="deleteForm" onsubmit="return confirmDeletion();">
        <div class="table-wrap">
            <table>
                <thead><tr><th class="checkbox-col"><input type="checkbox" id="selectAll"></th><th>ID</th><th>Invoice No.</th><th>Facility</th><th>District</th><th>Upload Date</th><th>Month</th><th>Uploaded By</th><th>Delivery Point</th></tr></thead>
                <tbody>
                    <?php if (count($records) > 0): ?>
                        <?php foreach ($records as $row): ?>
                            <tr>
                                <td class="checkbox-col"><input type="checkbox" name="delete_ids[]" value="<?php echo $row['id']; ?>" class="row-checkbox"></td>
                                <td><?php echo $row['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($row['InvoiceNo_str']); ?></strong></td>
                                <td><?php echo htmlspecialchars($row['facility']); ?></td>
                                <td><?php echo htmlspecialchars($row['district']); ?></td>
                                <td><?php echo date('d M Y', strtotime($row['upload_date'])); ?></td>
                                <td><?php echo htmlspecialchars($row['upload_month']); ?></td>
                                <td><?php echo htmlspecialchars($row['uploaded_by']); ?></td>
                                <td><?php echo htmlspecialchars($row['del_point']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="9" class="no-data">No records found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <div class="actions-bar">
            <button type="submit" class="btn btn-danger" id="deleteBtn" disabled>🗑️ Delete Selected</button>
            <span id="selectedCount" style="font-size:14px;color:#5e6f88;">0 selected</span>
            <span style="margin-left:auto;font-size:13px;color:#5e6f88;">Page <?php echo $page; ?> of <?php echo max(1, $total_pages); ?></span>
        </div>
    </form>

    <?php if ($total_pages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?><a href="?page=<?php echo $page-1; ?>&facility=<?php echo urlencode($facility_filter); ?>">‹ Prev</a><?php else: ?><span class="disabled">‹ Prev</span><?php endif; ?>
            <?php
            $start = max(1, $page - 2);
            $end = min($total_pages, $page + 2);
            if ($start > 1) echo '<a href="?page=1&facility='.urlencode($facility_filter).'">1</a> ... ';
            for ($i = $start; $i <= $end; $i++):
                if ($i == $page): ?><span class="current"><?php echo $i; ?></span><?php else: ?><a href="?page=<?php echo $i; ?>&facility=<?php echo urlencode($facility_filter); ?>"><?php echo $i; ?></a><?php endif;
            endfor;
            if ($end < $total_pages) echo ' ... <a href="?page='.$total_pages.'&facility='.urlencode($facility_filter).'">'.$total_pages.'</a>';
            ?>
            <?php if ($page < $total_pages): ?><a href="?page=<?php echo $page+1; ?>&facility=<?php echo urlencode($facility_filter); ?>">Next ›</a><?php else: ?><span class="disabled">Next ›</span><?php endif; ?>
        </div>
    <?php endif; ?>

    <a href="../index.php" class="back-link">← Return to Dashboard</a>
</div>

<script>
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.row-checkbox');
    const deleteBtn = document.getElementById('deleteBtn');
    const selectedCount = document.getElementById('selectedCount');

    function updateSelectionStatus() {
        const checked = document.querySelectorAll('.row-checkbox:checked').length;
        const total = checkboxes.length;
        selectedCount.textContent = checked + ' selected';
        deleteBtn.disabled = (checked === 0);
        if (selectAll) {
            if (checked === total) { selectAll.indeterminate = false; selectAll.checked = true; }
            else if (checked === 0) { selectAll.indeterminate = false; selectAll.checked = false; }
            else { selectAll.indeterminate = true; }
        }
    }
    if (selectAll) {
        selectAll.addEventListener('change', function() {
            const isChecked = this.checked;
            checkboxes.forEach(cb => cb.checked = isChecked);
            updateSelectionStatus();
        });
    }
    checkboxes.forEach(cb => cb.addEventListener('change', updateSelectionStatus));
    updateSelectionStatus();

    function confirmDeletion() {
        const checked = document.querySelectorAll('.row-checkbox:checked');
        if (checked.length === 0) { alert('Please select at least one record.'); return false; }
        return confirm('Delete ' + checked.length + ' record(s)? This cannot be undone.');
    }
</script>
</body>
</html>