<?php
// trash.php
// Admin-only. Lists soft-deleted (Deleted_At IS NOT NULL) jobs and lets an
// admin restore them back into the active register (restore_job.php).
//
// STRICT PROJECT RULE: soft delete only, never hard delete — there is
// deliberately NO "permanently delete" / "empty trash" action anywhere on
// this page. A job that lands here (via delete_job.php) stays here,
// restorable, forever.

require_once 'includes/auth.php';
require_role(['admin']);

require_once 'db.php';

$me = current_user();

$stmt = $pdo->query(
    "SELECT j.*, u.Name AS DeletedByName
     FROM tbl_jobs j
     LEFT JOIN tbl_users u ON u.UserID = j.Updated_By
     WHERE j.Deleted_At IS NOT NULL
     ORDER BY j.Deleted_At DESC"
);
$trashedJobs = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
    
    <meta name="csrf-token" content="<?= htmlspecialchars(csrf_token()); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trash — Liftek</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', Arial, sans-serif; }
        .table-header { background-color: #2c3e50; color: #fff; }
        #toastContainer { position: fixed; top: 16px; right: 16px; z-index: 2000; }
    </style>
</head>
<body class="bg-light">

<div id="toastContainer"></div>

<div class="container-fluid py-4 px-4">

    <div class="d-flex justify-content-between align-items-center mb-4 pb-2 border-bottom">
        <div>
            <h2 class="fw-bold text-danger m-0"><i class="fa-solid fa-trash me-2"></i>TRASH</h2>
            <p class="text-muted small m-0">Soft-deleted jobs. Nothing here is ever permanently erased — restore any job back to the active register at any time.</p>
        </div>
        <div>
            <a href="index.php" class="btn btn-outline-primary fw-bold"><i class="fa-solid fa-arrow-left me-1"></i> Back to Register</a>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-header">
                    <tr>
                        <th class="ps-3">Job No</th>
                        <th>Client Name</th>
                        <th>Category</th>
                        <th>Item Name</th>
                        <th>Deleted At</th>
                        <th>Deleted By</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody id="trashTableBody">
                    <?php if (count($trashedJobs) > 0): ?>
                        <?php foreach ($trashedJobs as $j): ?>
                            <tr data-job-id="<?= (int) $j['ID']; ?>">
                                <td class="ps-3 fw-bold text-primary"><?= htmlspecialchars($j['Job_No']); ?></td>
                                <td class="fw-semibold"><?= htmlspecialchars($j['Client_Name'] ?? 'N/A'); ?></td>
                                <td><span class="badge bg-secondary"><?= htmlspecialchars($j['Category'] ?? 'N/A'); ?></span></td>
                                <td><?= htmlspecialchars($j['Item_Name'] ?? 'N/A'); ?></td>
                                <td><?= htmlspecialchars($j['Deleted_At'] ?? '-'); ?></td>
                                <td><?= htmlspecialchars($j['DeletedByName'] ?? '-'); ?></td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-success fw-bold js-restore-job" data-job-id="<?= (int) $j['ID']; ?>">
                                        <i class="fa-solid fa-trash-arrow-up me-1"></i> Restore
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">Trash is empty.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

<script>
function showToast(message, isError) {
    var container = document.getElementById('toastContainer');
    var toast = document.createElement('div');
    toast.className = 'alert ' + (isError ? 'alert-danger' : 'alert-success') + ' shadow-sm mb-2';
    toast.style.minWidth = '280px';
    toast.textContent = message;
    container.appendChild(toast);
    setTimeout(function () { toast.remove(); }, 4000);
}

document.querySelectorAll('.js-restore-job').forEach(function (btn) {
    btn.addEventListener('click', function () {
        if (!confirm('Restore this job back to the active register?')) return;
        var jobId = btn.getAttribute('data-job-id');
        var formData = new FormData();
        formData.append('job_id', jobId);
        formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);

        fetch('restore_job.php', { method: 'POST', body: formData })
            .then(function (r) {
                if (r.status === 401) { window.location.href = 'login.php'; return Promise.reject(new Error('Session expired.')); }
                return r.text().then(function (text) {
                    var data;
                    try { data = JSON.parse(text); }
                    catch (e) { throw new Error('Unexpected server response (status ' + r.status + '). Please refresh the page and try again.'); }
                    return data;
                });
            })
            .then(function (data) {
                showToast(data.message, data.status !== 'success');
                if (data.status === 'success') {
                    var row = document.querySelector('tr[data-job-id="' + jobId + '"]');
                    if (row) row.remove();
                }
            })
            .catch(function (err) { showToast(err.message, true); });
    });
});
</script>

</body>
</html>
