<?php
// admin/pins/view_pins.php
$projectRoot = dirname(dirname(__DIR__));
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// --- NEW RESTRICTION START ---
// Strict Security: Only Super Admin can view PIN codes and logs.
// Sub-admins and Teachers are redirected back.
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../dashboard.php?error=unauthorized");
    exit();
}
// --- NEW RESTRICTION END ---

// --- 1. HANDLE DELETE ACTION ---
if (isset($_GET['delete_id'])) {
    $id = $_GET['delete_id'];
    $stmt = $pdo->prepare("DELETE FROM pins WHERE id = ?");
    $stmt->execute([$id]);
    header("Location: view_pins.php?msg=deleted");
    exit();
}

// --- 2. HANDLE BULK DELETE USED PINS ---
if (isset($_GET['clear_used'])) {
    $stmt = $pdo->prepare("DELETE FROM pins WHERE status = 'used'");
    $stmt->execute();
    header("Location: view_pins.php?msg=bulk_deleted");
    exit();
}

$sql = "SELECT p.*, s.fullname as student_name 
        FROM pins p 
        LEFT JOIN students s ON p.student_id = s.id 
        ORDER BY p.created_at DESC";
$pins = $pdo->query($sql)->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View PINs | <?php echo htmlspecialchars($school_name); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --success: #27ae60; --danger: #e74c3c; --warning: #e67e22; --accent: #e67e22; }
        
        body { font-family: 'Inter', 'Segoe UI', sans-serif; background: #f4f7f6; margin: 0; padding: 10px; color: #333; }
        .container { background: white; padding: 20px; border-radius: 12px; max-width: 1100px; margin: 10px auto; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
        
        /* Layout & Header */
        .header-section { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; margin-bottom: 25px; border-bottom: 2px solid #eee; padding-bottom: 15px; }
        .back-link { text-decoration: none; color: #3498db; font-weight: 600; font-size: 14px; }
        .admin-badge { background: #fee2e2; color: #dc2626; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; text-transform: uppercase; margin-bottom: 5px; display: inline-block; }
        
        /* Action Buttons */
        .btn-group { display: flex; gap: 10px; flex-wrap: wrap; }
        .btn { padding: 10px 18px; border-radius: 6px; text-decoration: none; font-size: 13px; font-weight: bold; border: none; cursor: pointer; transition: 0.3s; display: inline-flex; align-items: center; gap: 5px; }
        .print-btn { background: var(--primary); color: white; }
        .clear-btn { background: var(--warning); color: white; }
        .btn:hover { opacity: 0.9; transform: translateY(-1px); }

        /* Table Styling */
        table { width: 100%; border-collapse: collapse; margin-top: 10px; border-radius: 8px; overflow: hidden; }
        th { background: var(--primary); color: white; padding: 15px; text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; }
        td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; }
        
        code { background: #f8f9fa; padding: 4px 8px; border-radius: 4px; color: #d63384; font-weight: bold; }
        .status-unused { color: var(--success); font-weight: bold; }
        .status-used { color: var(--danger); font-weight: bold; }
        .delete-link { color: var(--danger); text-decoration: none; font-weight: bold; }

        /* Responsive Mobile Layout */
        @media (max-width: 768px) {
            .header-section { flex-direction: column; align-items: flex-start; }
            .btn-group { width: 100%; }
            .btn { flex: 1; justify-content: center; }

            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            tr { border: 1px solid #eee; margin-bottom: 15px; border-radius: 10px; padding: 10px; background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
            td { border: none; position: relative; padding-left: 50%; text-align: right; min-height: 25px; }
            td:before { 
                position: absolute; left: 15px; width: 40%; padding-right: 10px; 
                white-space: nowrap; text-align: left; font-weight: bold; color: #7f8c8d;
                content: attr(data-label); 
            }
        }

        @media print {
            .back-link, .btn-group, .delete-link, .admin-badge { display: none !important; }
            .container { box-shadow: none; border: none; width: 100%; max-width: 100%; }
            th { background: #eee !important; color: black !important; border: 1px solid #ddd; }
            td { border: 1px solid #ddd; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header-section">
        <div>
            <a href="../dashboard.php" class="back-link"><i class="fa fa-arrow-left"></i> Dashboard</a><br>
            <span class="admin-badge"><i class="fa fa-lock"></i> Super Admin Only</span>
            <h2 style="margin: 5px 0 0 0;">Result Checker PINs</h2>
        </div>
        <div class="btn-group">
            <a href="view_pins.php?clear_used=true" class="btn clear-btn" onclick="return confirm('Delete ALL used PINs?')">
                <i class="fa fa-broom"></i> Clear Used
            </a>
            <button onclick="window.print()" class="btn print-btn">
                <i class="fa fa-print"></i> Print List
            </button>
        </div>
    </div>

    <?php if(isset($_GET['msg'])): ?>
        <div style="background: #d4edda; color: #15803d; padding: 12px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #bbf7d0;">
            <i class="fa fa-check-circle"></i> 
            <?php 
                if($_GET['msg'] == 'deleted') echo "PIN deleted successfully.";
                if($_GET['msg'] == 'bulk_deleted') echo "All used PINs have been cleared."; 
            ?>
        </div>
    <?php endif; ?>

    <p style="font-size: 14px; color: #666;">Total PINs in Records: <strong><?php echo count($pins); ?></strong></p>

    <table>
        <thead>
            <tr>
                <th>Serial No.</th>
                <th>PIN Code</th>
                <th>Status</th>
                <th>Used By</th>
                <th>Generated</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($pins as $p): ?>
            <tr>
                <td data-label="Serial No."><code><?php echo $p['serial_number']; ?></code></td>
                <td data-label="PIN Code"><strong><?php echo $p['pin_code']; ?></strong></td>
                <td data-label="Status">
                    <span class="<?php echo ($p['status'] == 'unused') ? 'status-unused' : 'status-used'; ?>">
                        <?php echo strtoupper($p['status']); ?>
                    </span>
                </td>
                <td data-label="Used By"><?php echo htmlspecialchars($p['student_name'] ?? '---'); ?></td>
                <td data-label="Generated"><?php echo date('M d, Y', strtotime($p['created_at'])); ?></td>
                <td data-label="Action">
                    <a href="view_pins.php?delete_id=<?php echo $p['id']; ?>" 
                       class="delete-link" 
                       onclick="return confirm('Delete this PIN?')">
                       <i class="fa fa-trash-alt"></i> Delete
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if(count($pins) == 0): ?>
                <tr><td colspan="6" style="text-align:center; padding: 40px; color: #999;">No PINs generated yet.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

</body>
</html>