<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../classes/User.php';

if (isLoggedIn()) {
    $role = $_SESSION['role'] ?? 'student';
    if (in_array($role, ['admin', 'super_admin'], true)) {
        redirect(APP_URL . '/cms/dashboard.php');
    } elseif ($role === 'regional_admin') {
        redirect('dashboards/regional_admin.php');
    } elseif ($role === 'instructor') {
        redirect('dashboards/instructor.php');
    } else {
        redirect('dashboard.php');
    }
}

$user = new User();
$error = null;
$success = getFlashMessage('success');
$flashError = getFlashMessage('error');
if ($flashError) {
    $error = $flashError;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);

    try {
        $userData = $user->login($username, $password, $remember);
        $role = $_SESSION['role'] ?? 'student';
        if (in_array($role, ['admin', 'super_admin'], true)) {
            redirect(APP_URL . '/cms/dashboard.php');
        } elseif ($role === 'regional_admin') {
            redirect('dashboards/regional_admin.php');
        } elseif ($role === 'instructor') {
            redirect('dashboards/instructor.php');
        } else {
            redirect('dashboard.php');
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - SmartThink</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #fdfcfb 0%, #f9fafb 40%, #fef3c7 100%);
        }

        .login-page {
            width: 100%;
            padding: 1.5rem;
        }

        .login-shell {
            max-width: 1040px;
            margin: 0 auto;
            background: #f9fafb;
            border-radius: 32px;
            box-shadow: 0 28px 80px rgba(15, 23, 42, 0.18);
            display: flex;
            overflow: hidden;
        }

        .login-left {
            flex: 0 0 60%;
            padding: 3rem 3.5rem;
            background: radial-gradient(circle at top left, #fefce8, #f9fafb 55%, #f4f4ff 100%);
            color: #0f172a;
        }

        .login-brand {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 2.5rem;
        }

        .login-brand-logo {
            width: 40px;
            height: 40px;
            border-radius: 999px;
            background: #fef9c3;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 6px 18px rgba(234, 179, 8, 0.45);
        }

        .login-brand-logo i {
            color: #f59e0b;
        }

        .login-brand-text {
            font-weight: 600;
            letter-spacing: 0.04em;
            font-size: 0.95rem;
        }

        .login-heading {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.35rem;
        }

        .login-subtitle {
            font-size: 0.9rem;
            color: #6b7280;
            margin-bottom: 1.75rem;
        }

        .form-label {
            font-size: 0.8rem;
            color: #4b5563;
        }

        .form-control,
        .form-check-input {
            background-color: #f9fafb;
            border-color: #e5e7eb;
            color: #111827;
            border-radius: 999px;
            padding-left: 1.15rem;
            padding-right: 1.15rem;
            height: 46px;
            font-size: 0.9rem;
        }

        .form-control::placeholder {
            color: #9ca3af;
        }

        .form-control:focus,
        .form-check-input:focus {
            border-color: #fb923c;
            box-shadow: 0 0 0 1px rgba(251, 146, 60, 0.6);
            background-color: #fefce8;
            color: #111827;
        }

        .form-check-input {
            width: 1rem;
            height: 1rem;
            border-radius: 0.5rem;
        }

        .login-submit-btn {
            background: linear-gradient(90deg, #facc15, #fb923c);
            border: none;
            border-radius: 999px;
            font-weight: 600;
            color: #111827;
            height: 48px;
            font-size: 0.95rem;
        }

        .login-submit-btn:hover {
            background: linear-gradient(90deg, #eab308, #f97316);
        }

        .login-helper-text {
            font-size: 0.8rem;
            color: #9ca3af;
        }

        .login-footer-text {
            margin-top: 2rem;
            font-size: 0.75rem;
            color: #9ca3af;
        }

        .text-muted-link {
            color: #9ca3af;
            text-decoration: none;
        }

        .text-muted-link:hover {
            color: #111827;
        }

        .alert {
            border-radius: 0.75rem;
            font-size: 0.85rem;
        }

        .login-right {
            flex: 0 0 40%;
            position: relative;
            background: #020617;
            padding: 1.75rem 1.75rem 1.75rem 0;
            display: flex;
            align-items: stretch;
        }

        .login-hero {
            position: relative;
            border-radius: 28px;
            overflow: hidden;
            width: 100%;
            background: url('../assets/images/login-hero.jpg') center center / cover no-repeat;
        }

        .login-hero::before {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, rgba(15, 23, 42, 0.35), rgba(15, 23, 42, 0.05));
        }

        .login-pill-card {
            position: absolute;
            top: 1.5rem;
            right: 1.5rem;
            padding: 0.65rem 1.25rem;
            border-radius: 999px;
            background: rgba(15, 23, 42, 0.88);
            color: #f9fafb;
            font-size: 0.75rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            z-index: 1;
        }

        .login-pill-dot {
            width: 8px;
            height: 8px;
            border-radius: 999px;
            background: #22c55e;
        }

        .login-calendar-card {
            position: absolute;
            left: 1.5rem;
            bottom: 1.75rem;
            padding: 0.9rem 1.15rem;
            border-radius: 1.25rem;
            background: rgba(248, 250, 252, 0.97);
            font-size: 0.75rem;
            color: #0f172a;
            display: inline-flex;
            align-items: center;
            gap: 0.75rem;
            box-shadow: 0 18px 40px rgba(15, 23, 42, 0.35);
            z-index: 1;
        }

        .login-calendar-dates {
            display: flex;
            gap: 0.35rem;
        }

        .login-calendar-date {
            width: 24px;
            height: 24px;
            border-radius: 999px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7rem;
            color: #6b7280;
        }

        .login-calendar-date.active {
            background: #0f172a;
            color: #f9fafb;
        }

        .login-avatars {
            position: absolute;
            right: 1.5rem;
            bottom: 1.75rem;
            display: flex;
            align-items: center;
            gap: 0.25rem;
            z-index: 1;
        }

        .login-avatar-circle {
            width: 34px;
            height: 34px;
            border-radius: 999px;
            border: 2px solid #f9fafb;
            background: #e5e7eb;
        }

        .login-avatar-circle:nth-child(2) {
            margin-left: -10px;
            background: #fecaca;
        }

        .login-avatar-circle:nth-child(3) {
            margin-left: -10px;
            background: #bfdbfe;
        }

        .login-avatar-more {
            margin-left: -10px;
            background: #0f172a;
            color: #f9fafb;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.7rem;
        }

        @media (max-width: 992px) {
            .login-shell {
                flex-direction: column;
                border-radius: 24px;
            }

            .login-left {
                padding: 2.25rem 1.75rem 2rem;
            }

            .login-right {
                padding: 0 1.25rem 1.4rem 1.25rem;
            }

            .login-hero {
                height: 260px;
            }
        }

        @media (max-width: 576px) {
            .login-page {
                padding: 1rem;
            }

            .login-left {
                padding: 2rem 1.3rem 1.75rem;
            }
        }
    </style>
</head>
<body>
<div class="login-page">
    <div class="login-shell">
        <div class="login-left">
            <div class="login-brand">
                <div class="login-brand-logo">
                    <i class="fas fa-graduation-cap"></i>
                </div>
                <div class="login-brand-text">SmartThink</div>
            </div>

            <h1 class="login-heading">Welcome back</h1>
            <p class="login-subtitle">Sign in to continue your SmartThink learning journey and pick up where you left off.</p>

            <?php if (!empty($success)): ?>
                <div class="alert alert-success py-2 mb-3" role="alert">
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($error)): ?>
                <div class="alert alert-danger py-2 mb-3" role="alert">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>

            <form method="post" novalidate>
                <div class="mb-3">
                    <label for="username" class="form-label">Username or Email</label>
                    <input type="text" class="form-control" id="username" name="username" required autofocus>
                </div>

                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" class="form-control" id="password" name="password" required>
                </div>

                <div class="d-flex justify-content-between align-items-center mb-4">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" value="1" id="remember" name="remember">
                        <label class="form-check-label" for="remember">
                            Remember me
                        </label>
                    </div>
                    <a href="forgot_password.php" class="text-muted-link small">Forgot password?</a>
                </div>

                <button type="submit" class="btn w-100 mb-2 login-submit-btn">
                    <i class="fas fa-sign-in-alt me-2"></i>Login
                </button>

                <div class="login-helper-text mt-2">
                    By continuing, you agree to SmartThink's terms and privacy policy.
                </div>

                <div class="text-center small text-muted mt-3">
                    Don't have an account?
                    <a href="register.php" class="text-muted-link">Create one</a>
                </div>
            </form>

            <div class="login-footer-text">
                &copy; <?php echo date('Y'); ?> SmartThink. All rights reserved.
            </div>
        </div>
        <div class="login-right d-none d-md-flex">
            <div class="login-hero">
                <div class="login-pill-card">
                    <span class="login-pill-dot"></span>
                    <span id="loginHeroTimeLabel">Current time: --:--</span>
                </div>
                <div class="login-calendar-card">
                    <div>
                        <div class="fw-semibold" style="font-size: 0.78rem;" id="loginCalendarWeekLabel">This week</div>
                        <div style="font-size: 0.7rem; color: #6b7280;" id="loginCalendarDateLabel"></div>
                    </div>
                    <div class="login-calendar-dates" id="loginCalendarDates"></div>
                </div>
                <div class="login-avatars">
                    <div class="login-avatar-circle"></div>
                    <div class="login-avatar-circle"></div>
                    <div class="login-avatar-circle"></div>
                    <div class="login-avatar-circle login-avatar-more">+3</div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    (function () {
        function updateClock() {
            var timeLabel = document.getElementById('loginHeroTimeLabel');
            if (!timeLabel) return;
            var now = new Date();
            var options = { hour: '2-digit', minute: '2-digit' };
            var timeString = now.toLocaleTimeString([], options);
            timeLabel.textContent = 'Current time: ' + timeString;
        }

        function buildCurrentWeekCalendar() {
            var datesContainer = document.getElementById('loginCalendarDates');
            if (!datesContainer) return;
            datesContainer.innerHTML = '';

            var now = new Date();
            var weekday = now.getDay(); // 0 (Sun) - 6 (Sat)
            // Start week on Monday
            var diffToMonday = (weekday === 0 ? -6 : 1 - weekday);
            var monday = new Date(now);
            monday.setDate(now.getDate() + diffToMonday);

            for (var i = 0; i < 7; i++) {
                var d = new Date(monday);
                d.setDate(monday.getDate() + i);
                var span = document.createElement('div');
                span.className = 'login-calendar-date';
                span.textContent = d.getDate();
                if (d.toDateString() === now.toDateString()) {
                    span.classList.add('active');
                }
                datesContainer.appendChild(span);
            }

            var weekLabel = document.getElementById('loginCalendarWeekLabel');
            if (weekLabel) {
                weekLabel.textContent = 'This week';
            }
            var dateLabel = document.getElementById('loginCalendarDateLabel');
            if (dateLabel) {
                var dateOptions = { weekday: 'short', month: 'short', day: 'numeric' };
                dateLabel.textContent = now.toLocaleDateString([], dateOptions);
            }
        }

        document.addEventListener('DOMContentLoaded', function () {
            buildCurrentWeekCalendar();
            updateClock();
            // Update clock every minute
            setInterval(updateClock, 60000);
        });
    })();
</script>
</body>
</html>
