<?php
session_start();
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

// ADMIN CHECK LOGIC
$is_admin = isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1;

require_once 'pdo_config.php'; // Your PDO connection file

$username = isset($_SESSION['username']) ? $_SESSION['username'] : 'weew';

// Date setup
date_default_timezone_set('Asia/Manila');
$current_day = date('l');
$current_date = date('F j, Y');

// LICENSE EXPIRY SECTION (uses license_keys table)
$expiry_str = "";
$status_str = "";
try {
    $stmt = $pdo->query("SELECT valid_until FROM license_keys WHERE is_active = 1 ORDER BY valid_until DESC LIMIT 1");
    if ($license = $stmt->fetch()) {
        $expiry_date = $license['valid_until'];
        $expiry = strtotime($expiry_date);
        $today = strtotime(date('Y-m-d'));
        $days_left = ($expiry - $today) / 86400;
        if ($days_left < 0) {
            $status_str = "<span style='color:red;font-weight:bold;'>Expired</span>";
            $expiry_str = date('F d, Y', $expiry);
        } else {
            $status_str = "<span style='color:green;font-weight:bold;'>Active</span> &mdash; <span style='#1679ff;'>" . intval($days_left) . " days left</span>";
            $expiry_str = date('F d, Y', $expiry);
        }
    } else {
        $status_str = "<span style='color:gray;'>No license info found.</span>";
    }
} catch (Exception $e) {
    $status_str = "<span style='color:red;'>License table error: " . htmlspecialchars($e->getMessage()) . "</span>";
}

// CHECKED-IN STUDENTS SUMMARY
$checkedin = 0;
try {
    $today = date('Y-m-d');
    $stmt = $pdo->query("SELECT COUNT(DISTINCT lrn) as checkedin FROM checkins WHERE scan_date = '$today' AND (am_in IS NOT NULL OR pm_in IS NOT NULL)");
    if ($row = $stmt->fetch()) {
        $checkedin = $row['checkedin'];
    }
} catch (Exception $e) {
    $checkedin = 0;
}

// Show backup error message if set
$msg = "";
if (isset($_SESSION['error'])) {
    $msg = $_SESSION['error'];
    unset($_SESSION['error']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"/>
    <style>
        :root {
            --bg: #181818;
            --card: #232323;
            --text: #fff;
            --subtle: #b5c6e0;
        }
        body.light {
            --bg: #f6f6fa;
            --card: #fff;
            --text: #232323;
            --subtle: #575757;
        }
        body {
            background: var(--bg);
            min-height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
            color: var(--text);
            transition: background 0.3s, color 0.3s;
        }
        .toggle-mode {
            position: fixed;
            left: 28px;
            top: 20px;
            background: none;
            border: none;
            font-size: 1.7em;
            color: var(--subtle);
            cursor: pointer;
            z-index: 100;
            transition: color 0.2s;
        }
        .toggle-mode:active { transform: scale(1.2);}
        .user {
            position: absolute;
            right: 40px;
            top: 28px;
            color: var(--subtle);
            font-size: 1.1em;
        }
        .user a.logout {
            color: #f99;
            text-decoration: underline;
            margin-left: 8px;
            font-size: 1em;
        }
        .center-box {
            background: var(--card);
            border-radius: 30px;
            max-width: 500px;
            margin: 60px auto 0 auto;
            box-shadow: 0 6px 32px #0007;
            padding: 42px 30px 36px 30px;
            display: flex;
            flex-direction: column;
            align-items: center;
            transition: background 0.3s;
        }
        .logo {
            width: 110px;
            height: 110px;
            object-fit: contain;
            margin-bottom: 12px;
        }
        .title {
            font-size: 2em;
            font-weight: 700;
            margin: 8px 0 12px 0;
            color: var(--text);
            letter-spacing: 1px;
            text-align: center;
        }
        .date-today {
            color: var(--subtle);
            font-size: 1.08em;
            margin-bottom: 12px;
            margin-top: -10px;
            text-align: center;
        }
        .license-section {
            color: var(--subtle);
            background: rgba(22,121,255,0.06);
            border-radius: 9px;
            padding: 10px 10px 8px 10px;
            margin-bottom: 25px;
            margin-top: 0;
            text-align: center;
            font-size: 1.08em;
        }
        .summary-box {
            margin-bottom: 18px;
            background: #23262b;
            color: #fff;
            border-radius: 10px;
            padding: 14px 18px;
            font-size: 1.1em;
            box-shadow: 0 1px 6px 0 #0002;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .summary-box a {
            margin-left: 22px;
            padding: 7px 18px;
            border-radius: 7px;
            background: #198754;
            color: #fff;
            font-weight: bold;
            text-decoration: none;
            box-shadow: 0 1px 4px #0002;
            transition: background 0.2s;
        }
        .summary-box a:hover {
            background: #145c32;
        }
        .btn-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            grid-gap: 22px;
            width: 100%;
        }
        .dash-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 95px;
            border-radius: 16px;
            font-size: 1.13em;
            font-weight: bold;
            color: #fff;
            text-decoration: none;
            box-shadow: 0 2px 9px #0005;
            transition: transform 0.08s, box-shadow 0.1s, background 0.2s, color 0.2s;
        }
        .dash-btn:active, .dash-btn:hover {
            transform: scale(1.05);
            box-shadow: 0 2px 16px #000a;
        }
        .dash-btn i {
            font-size: 2.1em;
            margin-bottom: 7px;
        }
        .btn-attendance { background: #1679ff; }
        .btn-qr        { background: #1cc49d; }
        .btn-students  { background: #ffd93d; color: #222;}
        .btn-sf2       { background: #fd6e4c; }
        .btn-absent    { background: #a259d9; }
        .btn-backup    { background: #4ecca3; color: #222; }
        .btn-import    { background: #f49d1a; color: #222; }
        .btn-sf1       { background: #328a3e; }
        .btn-word      { background: #ff8c32; color: #222; } /* New button */
        .btn-webform   { background: #bb2d3b; color: #fff; } /* Red for sf2_webform.php */
        body.light .dash-btn    { color: #232323; }
        body.light .btn-attendance { background: #e3f0ff;}
        body.light .btn-qr        { background: #bbf6e1;}
        body.light .btn-students  { background: #fffbe0;}
        body.light .btn-sf2       { background: #ffe3d6;}
        body.light .btn-absent    { background: #eadcff;}
        body.light .btn-backup    { background: #c9ffe3;}
        body.light .btn-import    { background: #fff3d0;}
        body.light .btn-sf1       { background: #e2fbe2; color: #222; }
        body.light .btn-word      { background: #ffe3d6; color: #222; }
        body.light .btn-webform   { background: #ffdad6; color: #bb2d3b; }
        @media (max-width: 620px) {
            .center-box { max-width: 98vw; padding: 18px 4vw 28px 4vw;}
            .btn-grid { grid-template-columns: 1fr 1fr; grid-gap: 11px;}
        }
        @media (max-width: 430px) {
            .btn-grid { grid-template-columns: 1fr; }
        }
        .msg {
            margin: 14px 0 0 0;
            color: #f99;
            font-weight: bold;
            font-size: 1.1em;
        }
        /* Modal styles */
        #backupModal {
            display:none;position:fixed;top:0;left:0;width:100vw;height:100vh;
            background:rgba(0,0,0,0.5);z-index:999;
        }
        #backupModal .modal-content {
            background:#fff;color:#222;max-width:340px;margin:10% auto;
            padding:25px 22px;border-radius:12px;box-shadow:0 6px 32px #0007;position:relative;
        }
        #backupModal input[type="password"] {
            width:100%;padding:8px 10px;margin-bottom:14px;font-size:1em;border-radius:6px;border:1px solid #ccc;
        }
        #backupModal button {
            padding:8px 17px;border-radius:6px;border:none;font-size:1em;
        }
        #backupModal .download-btn { background:#1679ff;color:#fff; }
        #backupModal .cancel-btn { background:#ddd;color:#222;margin-left:12px; }
        #backupModal h3 { margin:0 0 14px 0;font-size:1.3em;}
    </style>
</head>
<body>
    <button class="toggle-mode" id="toggleModeBtn" title="Toggle dark/light mode">
        <i id="modeIcon" class="fa fa-moon"></i>
    </button>
    <div class="user">
        <i class="fa fa-user"></i> <?php echo htmlspecialchars($username); ?>
        | <a href="logout.php" class="logout">Logout</a>
    </div>
    <div class="center-box">
        <img class="logo" src="school_logo.png" alt="School Logo">
        <div class="title">SDAESI Dashboard</div>
        <div class="date-today">
            <?php echo "$current_day, $current_date"; ?>
        </div>
        <div class="license-section">
            <div>License Expiry: <b><?= $expiry_str ?></b></div>
            <div>Status: <?= $status_str ?></div>
        </div>
        <!-- Display error message -->
        <?php if ($msg): ?>
            <div class="msg"><?= htmlspecialchars($msg); ?></div>
        <?php endif; ?>
        <!-- Checked-in students summary and link -->
        <div class="summary-box">
            <span>✅ <b><?= $checkedin ?></b> students have checked in today (<?= date('F d, Y') ?>)</span>
            <a href="checkedin_students.php">View List</a>
        </div>
        <div class="btn-grid">
            <a href="logs.php" class="dash-btn btn-attendance">
                <i class="fa fa-clipboard-list"></i>Attendance Logs
            </a>
            <a href="sf2.php" class="dash-btn btn-sf2">
                <i class="fa fa-table"></i>SF2 Summary
            </a>
            <a href="absent.php" class="dash-btn btn-absent">
                <i class="fa fa-user-times"></i>Absent View
            </a>
            <a href="sf2_webform.php" class="dash-btn btn-webform">
                <i class="fa fa-file"></i>SF2 Web Form
            </a>
            <?php if ($is_admin): ?>
                <a href="generator.php" class="dash-btn btn-qr">
                    <i class="fa fa-qrcode"></i>Generate QR
                </a>
                <a href="students.php" class="dash-btn btn-students">
                    <i class="fa fa-users"></i>Student List
                </a>
                <!-- Backup Modal Button (triggers modal) -->
                <a href="#" onclick="document.getElementById('backupModal').style.display='block';return false;" class="dash-btn btn-backup">
                    <i class="fa fa-database"></i>Backup Database
                </a>
                <a href="import_sql.php" class="dash-btn btn-import">
                    <i class="fa fa-upload"></i>Import SQL
                </a>
                <a href="sf1_cleaned_format_generator.php" class="dash-btn btn-sf1">
                    <i class="fa fa-file-excel"></i>SF1 Generator
                </a>
                <!-- NEW BUTTON FOR QR WORD GENERATOR -->
                <a href="qr_with_name.php" class="dash-btn btn-word">
                    <i class="fa fa-file-word"></i>QR Word Generator
                </a>
            <?php endif; ?>
        </div>
    </div>
    <!-- BACKUP MODAL -->
    <div id="backupModal">
        <div class="modal-content">
            <h3>Enter Backup Password</h3>
            <form method="POST" action="backup.php">
                <input type="password" name="password" placeholder="Password" required>
                <button type="submit" class="download-btn">Download Backup</button>
                <button type="button" class="cancel-btn" onclick="document.getElementById('backupModal').style.display='none'">Cancel</button>
            </form>
        </div>
    </div>
    <script>
        // DARK/LIGHT TOGGLE
        const toggleBtn = document.getElementById('toggleModeBtn');
        const modeIcon = document.getElementById('modeIcon');
        function setMode(mode) {
            if (mode === 'light') {
                document.body.classList.add('light');
                modeIcon.className = 'fa fa-sun';
            } else {
                document.body.classList.remove('light');
                modeIcon.className = 'fa fa-moon';
            }
            localStorage.setItem('theme', mode);
        }
        (function() {
            let theme = localStorage.getItem('theme') || 'dark';
            setMode(theme);
        })();
        toggleBtn.onclick = function() {
            let theme = document.body.classList.contains('light') ? 'dark' : 'light';
            setMode(theme);
        }
        // Close modal on ESC
        document.addEventListener('keydown', function(e){
            if(e.key==="Escape") document.getElementById('backupModal').style.display='none';
        });
    </script>
</body>
</html>