<?php
// admin_moh_submissions.php
session_start();
require_once '../config.php'; // adjust path if needed

// AUTH: only admin allowed
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$admin_id = (int) $_SESSION['user_id'];

// helper
function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

// CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['csrf_token'];

$errors = [];
$messages = [];

/* ---------- Ensure columns exist: status, rejection_reason, approved_by, approved_at ---------- */
$cols = $conn->query("SHOW COLUMNS FROM moh_submissions LIKE 'status'");
if ($cols && $cols->num_rows === 0) {
    $conn->query("ALTER TABLE moh_submissions ADD status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending'");
}
$cols2 = $conn->query("SHOW COLUMNS FROM moh_submissions LIKE 'rejection_reason'");
if ($cols2 && $cols2->num_rows === 0) {
    $conn->query("ALTER TABLE moh_submissions ADD rejection_reason TEXT NULL");
}
$cols3 = $conn->query("SHOW COLUMNS FROM moh_submissions LIKE 'approved_by'");
if ($cols3 && $cols3->num_rows === 0) {
    $conn->query("ALTER TABLE moh_submissions ADD approved_by INT NULL, ADD approved_at DATETIME NULL");
}

/* ---------- Handle POST actions ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid CSRF token.';
    } else {
        // Approve single
        if (isset($_POST['approve'])) {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) {
                $errors[] = 'Invalid id.';
            } else {
                $stmt = $conn->prepare("UPDATE moh_submissions SET status='approved', approved_by = ?, approved_at = NOW() WHERE id = ? AND status = 'pending'");
                $stmt->bind_param("ii", $admin_id, $id);
                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) $messages[] = "Submission #$id approved.";
                    else $errors[] = "Submission #$id was not pending or not found.";
                } else {
                    $errors[] = 'DB error: ' . $stmt->error;
                }
                $stmt->close();
            }
        }

        // Reject single
        if (isset($_POST['reject'])) {
            $id = (int)($_POST['id'] ?? 0);
            $reason = trim($_POST['reject_reason'] ?? '');
            if ($id <= 0) {
                $errors[] = 'Invalid id.';
            } else {
                $stmt = $conn->prepare("UPDATE moh_submissions SET status='rejected', rejection_reason = ?, approved_by = ?, approved_at = NOW() WHERE id = ? AND status = 'pending'");
                $stmt->bind_param("sii", $reason, $admin_id, $id);
                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) $messages[] = "Submission #$id rejected.";
                    else $errors[] = "Submission #$id was not pending or not found.";
                } else {
                    $errors[] = 'DB error: ' . $stmt->error;
                }
                $stmt->close();
            }
        }

        // Delete single
        if (isset($_POST['delete_submission'])) {
            $id = (int)($_POST['delete_id'] ?? 0);
            if ($id <= 0) {
                $errors[] = 'Invalid id.';
            } else {
                $stmt = $conn->prepare("SELECT attachment_path FROM moh_submissions WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $res = $stmt->get_result();

                if ($row = $res->fetch_assoc()) {
                    $attachment = $row['attachment_path'];
                    $stmt->close();

                    $stmt2 = $conn->prepare("DELETE FROM moh_submissions WHERE id = ?");
                    $stmt2->bind_param("i", $id);
                    if ($stmt2->execute()) {
                        if (!empty($attachment)) {
                            $p = __DIR__ . '/' . $attachment;
                            if (file_exists($p)) @unlink($p);
                        }
                        $messages[] = "Submission #$id deleted.";
                    } else {
                        $errors[] = 'Delete failed: ' . $stmt2->error;
                    }
                    $stmt2->close();
                } else {
                    $errors[] = 'Submission not found.';
                    $stmt->close();
                }
            }
        }

        // Bulk approve
        if (isset($_POST['bulk_approve'])) {
            $ids = $_POST['ids'] ?? [];
            if (!is_array($ids) || empty($ids)) {
                $errors[] = 'Select at least one submission.';
            } else {
                $ids_clean = array_map('intval', $ids);
                $ids_clean = array_filter($ids_clean, fn($v) => $v > 0);

                if (empty($ids_clean)) {
                    $errors[] = 'Select at least one valid submission.';
                } else {
                    $ids_list = implode(',', $ids_clean);
                    $sql = "UPDATE moh_submissions
                            SET status='approved', approved_by = $admin_id, approved_at = NOW()
                            WHERE id IN ($ids_list) AND status = 'pending'";
                    if ($conn->query($sql)) {
                        $messages[] = 'Bulk approve executed. Affected: ' . $conn->affected_rows;
                    } else {
                        $errors[] = 'Bulk approve error: ' . $conn->error;
                    }
                }
            }
        }
    }

    // regenerate CSRF token
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
    $csrf = $_SESSION['csrf_token'];
}

/* ---------- Filters and fetch ---------- */
$filter = $_GET['filter'] ?? 'pending'; // pending | all | approved | rejected
$allowed = ['pending', 'all', 'approved', 'rejected'];
if (!in_array($filter, $allowed, true)) $filter = 'pending';

$where = "";
if ($filter === 'pending') $where = "WHERE s.status = 'pending'";
elseif ($filter === 'approved') $where = "WHERE s.status = 'approved'";
elseif ($filter === 'rejected') $where = "WHERE s.status = 'rejected'";

$sql = "SELECT s.*, u.username
        FROM moh_submissions s
        LEFT JOIN users u ON u.id = s.user_id
        $where
        ORDER BY s.created_at DESC";

$res = $conn->query($sql);
$submissions = [];
if ($res) {
    $submissions = $res->fetch_all(MYSQLI_ASSOC);
    $res->free();
} else {
    $errors[] = 'DB error: ' . $conn->error;
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Admin — MOH Submissions</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --bg:#f4f6fb;
    --card:#ffffff;
    --text:#000000;
    --muted:#555555;
    --border:#e5e7eb;
    --shadow:0 12px 30px rgba(0,0,0,0.08);
    --radius:18px;
    --sidebar:260px;
    --accent:#111111;
    --accent-2:#2b2b2b;
}

*{
    box-sizing:border-box;
}

html, body{
    margin:0;
    padding:0;
    overflow-x:hidden;
    background:var(--bg);
    color:var(--text);
    font-family: Arial, Helvetica, sans-serif;
}

a{
    text-decoration:none !important;
}

.container{
    margin-left: var(--sidebar);
    padding: 58px 18px 18px;
    min-height:100vh;
}

.page-header{
    color:#000;
    padding:14px 16px;
    border-radius:var(--radius);
    margin-bottom:0px;
}

.page-header h1{
  color: #000;
    margin:0;
    font-size:22px;
    font-weight:800;
    line-height:1.2;
}

.page-header p{
    margin:8px 0 0;
    font-size:14px;
    color:rgba(255,255,255,0.82);
}

.card{
    background:var(--card);
    border-radius:var(--radius);
    box-shadow:var(--shadow);
    border:1px solid var(--border);
    overflow:hidden;
}

.toolbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:14px;
    flex-wrap:wrap;
    padding:10px 12px;
    border-bottom:1px solid var(--border);
    background:#fafafa;
}

.small{
    color:var(--muted);
    font-size:13px;
}

.filter-group{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    align-items:center;
}

.btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    padding:7px 12px;
    font-size:13px;
    border-radius:12px;
    border:none;
    font-weight:700;
    cursor:pointer;
    background:#111111;
    color:#fff;
    transition:0.2s ease;
    white-space:nowrap;
}

.btn:hover{
    transform:translateY(-1px);
    box-shadow:0 8px 18px rgba(0,0,0,0.15);
}

.btn.ghost{
    background:#fff;
    color:#000;
    border:1px solid var(--border);
    box-shadow:none;
}

.btn.ghost:hover{
    background:#f8f8f8;
}

.notice{
    padding:12px 14px;
    border-radius:12px;
    margin:0 0 12px;
    font-size:14px;
}

.notice.success{
    background:#ecfdf3;
    color:#027a48;
    border:1px solid #abefc6;
}

.notice.error{
    background:#fef3f2;
    color:#b42318;
    border:1px solid #fecdca;
}

.bulk-bar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
    padding:10px 12px;
    border-bottom:1px solid var(--border);
    background:#fff;
}

.bulk-left{
    display:flex;
    align-items:center;
    gap:10px;
    flex-wrap:wrap;
}

.bulk-right{
    display:flex;
    align-items:center;
    gap:8px;
    flex-wrap:wrap;
}

.bulk-btn{
    background:#111111;
    color:#fff;
    border:none;
    border-radius:12px;
    padding:10px 16px;
    font-weight:700;
    cursor:pointer;
    transition:0.2s ease;
}

.bulk-btn:hover{
    transform:translateY(-1px);
    box-shadow:0 8px 18px rgba(0,0,0,0.15);
}

.table-wrap{
    overflow-x:auto;
}

.table{
    width:100%;
    min-width:1180px;
    border-collapse:collapse;
}

.table thead th{
    background:#000;
    color:#fff;
    font-size:13px;
    text-transform:uppercase;
    letter-spacing:.35px;
    padding:10px 10px;
    font-size:12px;
    border-bottom:1px solid #111;
    text-align:left;
    white-space:nowrap;
}

.table tbody td{
    padding:10px 10px;
    font-size:13px;
    border-bottom:1px solid #f1f1f1;
    font-size:14px;
    color:#000;
    vertical-align:top;
}

.table tbody tr:hover{
    background:#fafafa;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:5px 10px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    white-space:nowrap;
}

.badge.pending{
    background:#fff7ed;
    color:#92400e;
    border:1px solid #fed7aa;
}

.badge.approved{
    background:#ecfdf3;
    color:#065f46;
    border:1px solid #abefc6;
}

.badge.rejected{
    background:#fef2f2;
    color:#991b1b;
    border:1px solid #fecaca;
}

.actions{
    display:flex;
    align-items:center;
    gap:8px;
    flex-wrap:wrap;
}

.row-form{
    display:inline-flex;
    align-items:center;
    gap:8px;
    flex-wrap:wrap;
    margin:0;
}

.note-title{
    font-weight:700;
    color:#000;
    margin-bottom:4px;
}

.note-text{
    color:var(--muted);
    font-size:13px;
    line-height:1.5;
}

.empty{
    padding:28px 18px;
    text-align:center;
    color:var(--muted);
    font-size:14px;
}

.modal{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(2,6,23,0.55);
    align-items:center;
    justify-content:center;
    z-index:2000;
    padding:18px;
}

.modal-card{
    width:520px;
    max-width:100%;
    background:#fff;
    border-radius:18px;
    box-shadow:0 20px 50px rgba(0,0,0,0.25);
    overflow:hidden;
}

.modal-head{
    padding:16px 18px;
    border-bottom:1px solid var(--border);
    background:#fafafa;
}

.modal-head h3{
    margin:0;
    font-size:18px;
    color:#000;
}

.modal-body{
    padding:14px;
}

.modal-actions{
    display:flex;
    justify-content:flex-end;
    gap:8px;
    margin-top:14px;
    flex-wrap:wrap;
}

textarea{
    width:100%;
    min-height:120px;
    resize:vertical;
    padding:12px 14px;
    border-radius:12px;
    border:1px solid var(--border);
    outline:none;
    font-family:inherit;
    font-size:14px;
    color:#000;
    background:#fff;
}

textarea:focus{
    border-color:#111;
    box-shadow:0 0 0 4px rgba(17,17,17,0.08);
}

textarea::placeholder,
input::placeholder{
    color:#888;
}

.icon-link{
    color:#000;
    font-weight:700;
}

.icon-link:hover{
    text-decoration:underline;
}

@media(max-width:900px){
    .container{
        margin-left:0;
        padding:16px;
    }
}

@media(max-width:640px){
    .page-header{
        padding:18px;
    }

    .page-header h1{
        font-size:22px;
    }

    .toolbar,
    .bulk-bar{
        padding:14px;
    }

    .table{
        min-width:1080px;
    }
}
/* ================= MOBILE RESPONSIVE ================= */
@media (max-width: 768px) {

    /* HEADER FIX */
    body {
        padding-top: 65px;
    }

    /* CONTAINER FIX */
    .container {
        margin-left: 0 !important;
        padding: 12px;
    }

    /* HEADER TEXT */
    .page-header {
        padding: 12px;
    }

    .page-header h1 {
        font-size: 18px;
    }

    .page-header p {
        font-size: 12px;
    }

    /* TOOLBAR */
    .toolbar {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .filter-group {
        width: 100%;
        flex-wrap: wrap;
    }

    /* BUTTON */
    .btn {
        font-size: 12px;
        padding: 6px 10px;
    }

    /* TABLE SCROLL */
    .table-wrap {
        overflow-x: auto;
    }

    .table {
        min-width: 900px; /* important */
    }

    /* TABLE TEXT */
    .table th,
    .table td {
        font-size: 12px;
        padding: 8px;
        white-space: nowrap;
    }

    /* ACTION BUTTONS */
    .actions {
        flex-direction: column;
        align-items: flex-start;
        gap: 6px;
    }

    .row-form {
        flex-direction: column;
        align-items: flex-start;
    }

    /* MODAL FIX */
    .modal-card {
        width: 95%;
    }

    textarea {
        font-size: 13px;
    }
}
</style>
</head>
<body>

<?php include 'adminsidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="container">
    <div class="page-header" >
        <h1><i class="fa-solid fa-paper-plane"></i> Admin — MOH Submissions</h1>
        <p style="color: #000;">Review submissions, approve pending entries, reject with reason, or delete records.</p>
    </div>

    <?php foreach ($messages as $m): ?>
        <div class="notice success"><?php echo e($m); ?></div>
    <?php endforeach; ?>

    <?php foreach ($errors as $er): ?>
        <div class="notice error"><?php echo e($er); ?></div>
    <?php endforeach; ?>

    <div class="card">
        <div class="toolbar">
            <div class="small">Showing: <strong><?php echo e(ucfirst($filter)); ?></strong></div>
            <div class="filter-group">
                <a class="btn <?php echo $filter === 'pending' ? '' : 'ghost'; ?>" href="?filter=pending">Pending</a>
                <a class="btn <?php echo $filter === 'all' ? '' : 'ghost'; ?>" href="?filter=all">All</a>
                <a class="btn <?php echo $filter === 'approved' ? '' : 'ghost'; ?>" href="?filter=approved">Approved</a>
                <a class="btn <?php echo $filter === 'rejected' ? '' : 'ghost'; ?>" href="?filter=rejected">Rejected</a>
            </div>
        </div>

        <form method="post" id="bulkForm">
            <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">

            

            <div class="table-wrap">
                <table class="table">
                    <thead>
                        <tr>
                            <th style="width:48px;"></th>
                            <th style="width:80px;">ID</th>
                            <th>Title / Notes</th>
                            <th>Dept</th>
                            <th>Dossier</th>
                            <th style="width:140px;">Submitted On</th>
                            <th>By</th>
                            <th>Attachment</th>
                            <th style="width:120px;">Status</th>
                            <th style="width:260px;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($submissions)): ?>
                            <tr>
                                <td colspan="10">
                                    <div class="empty">No submissions found.</div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($submissions as $s): ?>
                                <tr>
                                    <td>
                                        <input type="checkbox" name="ids[]" value="<?php echo e($s['id']); ?>">
                                    </td>
                                    <td><?php echo e($s['id']); ?></td>
                                    <td>
                                        <div class="note-title"><?php echo e($s['title']); ?></div>
                                        <div class="note-text"><?php echo e(mb_strimwidth($s['notes'] ?? '', 0, 140, '...')); ?></div>
                                    </td>
                                    <td><?php echo e($s['department']); ?></td>
                                    <td><?php echo e($s['dossier_number']); ?></td>
                                    <td class="small"><?php echo e($s['submission_date'] ? date('Y-m-d', strtotime($s['submission_date'])) : '—'); ?></td>
                                    <td class="small"><?php echo e($s['username'] ?? '—'); ?></td>
                                    <td>
                                        <?php if (!empty($s['attachment_path']) && file_exists(__DIR__ . '/' . $s['attachment_path'])): ?>
                                            <a class="icon-link small" href="<?php echo e($s['attachment_path']); ?>" target="_blank">
                                                <i class="fa-solid fa-download"></i> View
                                            </a>
                                        <?php else: ?>
                                            <span class="small">—</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                            $st = strtolower($s['status'] ?? 'pending');
                                            if ($st === 'approved') echo '<span class="badge approved">Approved</span>';
                                            elseif ($st === 'pending') echo '<span class="badge pending">Pending</span>';
                                            else echo '<span class="badge rejected">Rejected</span>';
                                        ?>
                                    </td>
                                    <td>
                                        <div class="actions">
                                            <?php if (($s['status'] ?? 'pending') === 'pending'): ?>
                                                <form method="post" class="row-form">
                                                    <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                                    <input type="hidden" name="id" value="<?php echo e($s['id']); ?>">
                                                    <button class="btn" type="submit" name="approve" onclick="return confirm('Approve submission #<?php echo e($s['id']); ?>?');">
                                                        Approve
                                                    </button>
                                                    <button class="btn ghost" type="button" onclick="openReject(<?php echo e($s['id']); ?>)">
                                                        Reject
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <span class="small">—</span>
                                            <?php endif; ?>

                                            <form method="post" class="row-form">
                                                <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                                                <input type="hidden" name="delete_id" value="<?php echo e($s['id']); ?>">
                                                <button class="btn ghost" type="submit" name="delete_submission" onclick="return confirm('Delete submission #<?php echo e($s['id']); ?>?');">
                                                    Delete
                                                </button>
                                            </form>
                                        </div>

                                        <?php if (!empty($s['rejection_reason'])): ?>
                                            <div class="note-text" style="margin-top:8px;">
                                                <strong>Reason:</strong> <?php echo e(mb_strimwidth($s['rejection_reason'], 0, 140, '...')); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
</div>

<!-- Reject modal -->
<div id="rejectModal" class="modal">
    <div class="modal-card">
        <div class="modal-head">
            <h3>Reject submission</h3>
        </div>
        <div class="modal-body">
            <form method="post" id="rejectForm">
                <input type="hidden" name="csrf_token" value="<?php echo e($csrf); ?>">
                <input type="hidden" name="id" id="reject_id" value="">

                <label style="display:block;margin-bottom:8px;font-weight:700;color:#000;">Reason (optional)</label>
                <textarea name="reject_reason" id="reject_reason" placeholder="Enter rejection reason here..."></textarea>

                <div class="modal-actions">
                    <button class="btn ghost" type="button" onclick="closeReject()">Cancel</button>
                    <button class="btn" type="submit" name="reject">Reject</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function openReject(id){
    document.getElementById('reject_id').value = id;
    document.getElementById('reject_reason').value = '';
    document.getElementById('rejectModal').style.display = 'flex';
}

function closeReject(){
    document.getElementById('rejectModal').style.display = 'none';
}

document.getElementById('checkAll')?.addEventListener('change', function(e){
    const checked = e.target.checked;
    document.querySelectorAll('input[name="ids[]"]').forEach(cb => cb.checked = checked);
});

document.addEventListener('click', function(e){
    const modal = document.getElementById('rejectModal');
    if (e.target === modal) closeReject();
});
</script>

</body>
</html>