<?php
// delete.php - Manage Receipts: View, Filter, Delete, Paginate, Reindex

// Database connection
$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 = isset($_GET['per_page']) ? intval($_GET['per_page']) : 20;
$allowed_per_page = [20, 50, 100, 500];
if (!in_array($per_page, $allowed_per_page)) {
    $per_page = 20;
}

// ---- Handle messages from GET (reindex or other) ----
$message = '';
$message_type = '';
if (isset($_GET['msg']) && isset($_GET['msgtype'])) {
    $message = urldecode($_GET['msg']);
    $message_type = $_GET['msgtype'];
}

// ---- Handle POST: Delete selected records ----
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 after deletion
            $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();

            header("Location: delete.php?page=" . $page . "&facility=" . urlencode($facility_filter) . "&per_page=" . $per_page . "&msg=" . urlencode("Deleted $deleted_count record(s). Table reindexed.") . "&msgtype=success");
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            header("Location: delete.php?page=" . $page . "&facility=" . urlencode($facility_filter) . "&per_page=" . $per_page . "&msg=" . urlencode("Error: " . $e->getMessage()) . "&msgtype=error");
            exit;
        }
    } else {
        header("Location: delete.php?page=" . $page . "&facility=" . urlencode($facility_filter) . "&per_page=" . $per_page . "&msg=" . urlencode("No records selected.") . "&msgtype=warning");
        exit;
    }
}

// ---- Handle GET: Reindex table (maintenance) ----
if (isset($_GET['action']) && $_GET['action'] === 'reindex') {
    $conn->begin_transaction();
    try {
        $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");
            $next_id = 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();
        $msg = "Table reindexed successfully. Next AUTO_INCREMENT is " . $next_id . ".";
        $type = 'success';
    } catch (Exception $e) {
        $conn->rollback();
        $msg = "Error during reindex: " . $e->getMessage();
        $type = 'error';
    }
    header("Location: delete.php?page=" . $page . "&facility=" . urlencode($facility_filter) . "&per_page=" . $per_page . "&msg=" . urlencode($msg) . "&msgtype=" . $type);
    exit;
}

// ---- 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>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f0f4fb;
            padding: 30px 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
        }
        .container {
            max-width: 1280px;
            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;
        }
        .note {
            background: #f8faff;
            border-left: 4px solid #1a4f8a;
            padding: 14px 18px;
            border-radius: 10px;
            margin-bottom: 24px;
            font-size: 14px;
            color: #1a2d44;
            line-height: 1.6;
        }
        .note strong { color: #0b1b2f; }
        .note .btn-desc {
            display: inline-block;
            background: #eef3fa;
            padding: 0 8px;
            border-radius: 4px;
            font-weight: 600;
            font-size: 13px;
        }
        .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"], .filter-form input[type="number"] {
            padding: 8px 16px;
            border-radius: 10px;
            border: 1.5px solid #d0d9e6;
            background: #fafcff;
            font-size: 14px;
            transition: border-color 0.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 0.2s ease;
            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-warning {
            background: #f39c12;
            color: #fff;
        }
        .btn-warning:hover {
            background: #d68910;
            transform: translateY(-1px);
        }
        .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 0.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;
        }
        .per-page-form {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .per-page-form select {
            padding: 6px 12px;
            border-radius: 8px;
            border: 1.5px solid #d0d9e6;
            background: #fafcff;
            font-size: 14px;
        }
        .per-page-form label {
            font-weight: 500;
            color: #0b1b2f;
            font-size: 14px;
        }
        @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; }
            .per-page-form { flex-wrap: wrap; }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <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, delete, and maintain 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>

    <!-- Note: Purpose and Button Descriptions -->
    <div class="note">
        <strong>📌 About this page</strong><br>
        This page lists all receipt records from the database. You can:
        <ul style="margin: 6px 0 0 20px; padding-left: 0; list-style: disc;">
            <li><strong>Filter</strong> by facility using the dropdown above.</li>
            <li><strong>Select</strong> individual rows via checkboxes, or use <span class="btn-desc">Select All</span> (on the current page).</li>
            <li><strong>Delete</strong> selected records with the <span class="btn-desc" style="background:#c0392b;color:#fff;">🗑️ Delete Selected</span> button – this action is <strong>permanent</strong> and automatically re‑indexes the table.</li>
            <li><strong>Reindex</strong> the table manually with the <span class="btn-desc" style="background:#f39c12;color:#fff;">🔄 Reindex Table</span> button – resets the auto‑increment counter to the next available ID (useful after manual data operations).</li>
            <li><strong>Change page size</strong> using the “Rows per page” dropdown to display 20, 50, 100, or 500 records.</li>
            <li><strong>Navigate</strong> through pages with the pagination links at the bottom.</li>
        </ul>
        <em style="display:block; margin-top:6px; color:#5e6f88;">All changes are reflected immediately. Deletion and reindexing are transactional for safety.</em>
    </div>

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

    <!-- Top Bar: Filter + Stats + Per Page -->
    <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="hidden" name="per_page" value="<?php echo $per_page; ?>">
            <input type="submit" value="Apply Filter">
            <?php if (!empty($facility_filter)): ?>
                <a href="?facility=&per_page=<?php echo $per_page; ?>" class="btn btn-outline" style="padding:6px 14px;">Clear</a>
            <?php endif; ?>
        </form>

        <div style="display:flex; align-items:center; gap:16px; flex-wrap:wrap;">
            <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; ?>

            <!-- Per Page Selector -->
            <form method="get" class="per-page-form">
                <label for="per_page">Rows per page:</label>
                <select name="per_page" id="per_page" onchange="this.form.submit()">
                    <?php foreach ($allowed_per_page as $val): ?>
                        <option value="<?php echo $val; ?>" <?php echo ($per_page == $val) ? 'selected' : ''; ?>>
                            <?php echo $val; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" name="facility" value="<?php echo htmlspecialchars($facility_filter); ?>">
                <input type="hidden" name="page" value="1">
            </form>
        </div>
    </div>

    <!-- Records Table -->
    <form method="post" id="deleteForm" onsubmit="return confirmDeletion();">
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th class="checkbox-col">
                            <input type="checkbox" id="selectAll" title="Select all rows on this page">
                        </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>
            <a href="?action=reindex&facility=<?php echo urlencode($facility_filter); ?>&per_page=<?php echo $per_page; ?>&page=<?php echo $page; ?>" 
               class="btn btn-warning" 
               onclick="return confirm('Reindex the table? This will reset the auto-increment counter to the next available ID.')">
                🔄 Reindex Table
            </a>
            <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); ?>
                (<?php echo $total_records; ?> total)
            </span>
        </div>
    </form>

    <!-- Pagination -->
    <?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); ?>&per_page=<?php echo $per_page; ?>">‹ 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).'&per_page='.$per_page.'">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); ?>&per_page=<?php echo $per_page; ?>"><?php echo $i; ?></a>
                <?php endif;
            endfor;
            if ($end < $total_pages) {
                echo ' ... <a href="?page='.$total_pages.'&facility='.urlencode($facility_filter).'&per_page='.$per_page.'">'.$total_pages.'</a>';
            }
            ?>

            <?php if ($page < $total_pages): ?>
                <a href="?page=<?php echo $page+1; ?>&facility=<?php echo urlencode($facility_filter); ?>&per_page=<?php echo $per_page; ?>">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>
    (function() {
        'use strict';

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

        // Confirm before delete
        window.confirmDeletion = function() {
            const checked = document.querySelectorAll('.row-checkbox:checked');
            if (checked.length === 0) {
                alert('Please select at least one record to delete.');
                return false;
            }
            return confirm('Are you sure you want to delete ' + checked.length + ' selected record(s)?\nThis action cannot be undone.');
        };

        // For per-page dropdown auto-submit
        document.getElementById('per_page')?.addEventListener('change', function() {
            this.form.submit();
        });
    })();
</script>
</body>
</html>