<?php
/**
 * IBVTE – College Portal Login
 * Authenticates college users using the central Auth system
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../middleware.php';

if (!checkDBConnection()) exit;
$db = DB();

// If already logged in as college, redirect to dashboard
if (Auth()->isLoggedIn()) {
    if (Auth()->hasRole(['college'])) {
        header('Location: dashboard.php');
        exit;
    } else {
        // Admin/other session active
        // Only logout if we are NOT currently trying to impersonate
        if (($_GET['action'] ?? '') !== 'impersonate') {
            Auth()->logout();
            header('Location: login.php');
            exit;
        }
        // If we ARE impersonating, we let the logic below handle it
    }
}

$error   = '';
$success = '';

// Handle Admin Impersonation
$isImpersonating = false;
$impersonateUser = '';
$impersonateToken = '';

if (($_GET['action'] ?? '') === 'impersonate' && isset($_GET['user'], $_GET['itoken'])) {
    $tokenData = Auth()->verifyImpersonationToken($_GET['itoken']);
    if ($tokenData) {
        $isImpersonating = true;
        $impersonateUser = $_GET['user'];
        $impersonateToken = $_GET['itoken'];
        $success = "Admin mode: Ready to login as " . htmlspecialchars($impersonateUser);
    } else {
        $error = "Impersonation session expired or invalid.";
        // Log the failure for debugging
        logError('Impersonation Failed', [
            'token_received' => $_GET['itoken'],
            'user_received' => $_GET['user'],
            'session_user_id' => $_SESSION['user_id'] ?? 'none'
        ]);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $iToken   = $_POST['itoken'] ?? '';
    $captcha  = $_POST['captcha'] ?? '';

    if (!empty($iToken)) {
        // Process Impersonation Login (No captcha needed for admin bypass)
        $tokenData = Auth()->verifyImpersonationToken($iToken);
        if ($tokenData) {
            $result = Auth()->loginAs($tokenData['id']);
            if ($result['success']) {
                header('Location: dashboard.php');
                exit;
            } else {
                $error = $result['message'];
            }
        } else {
            $error = "Security token mismatch. Please try again from admin panel.";
        }
    } else {
        // Standard Login
        if (empty($username) || empty($password)) {
            $error = 'Please enter both College User ID and Password.';
        } else {
            // Verify Math Captcha
            $captchaVerify = Middleware()->verifyCaptcha($captcha, 'math');
            if (!$captchaVerify['success']) {
                $error = $captchaVerify['message'];
            } else {
                // Use the central Auth login
                $result = Auth()->login($username, $password, null, null);

                if ($result['success']) {
                    $user = Auth()->getUser();
                    if ($user && $user['role_id'] == ROLE_COLLEGE) {
                        try {
                            $db->insert('college_activity_logs', [
                                'college_id'  => $user['id'],
                                'action'      => 'LOGIN',
                                'description' => 'College portal login successful.',
                                'entity_type' => 'user',
                                'entity_id'   => $user['id'],
                                'ip_address'  => $_SERVER['REMOTE_ADDR'] ?? '',
                            ]);
                        } catch (Exception $e) { }
                        header('Location: dashboard.php');
                        exit;
                    } else {
                        Auth()->logout();
                        $error = 'This portal is for College accounts only.';
                    }
                } else {
                    $error = $result['message'];
                }
            }
        }
    }
}

// Generate math captcha for NEXT standard login attempt
$mathCaptcha = Middleware()->generateMathCaptcha();

$flash = getFlashMessage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>College Login – <?= APP_SHORT_NAME ?></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>
        :root { --primary: #3b0b7c; --secondary: #6c4ab6; --accent: #ffd700; }

        * { box-sizing: border-box; }

        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', Tahoma, sans-serif;
            padding: 20px;
        }

        .login-wrap {
            background: white;
            border-radius: 24px;
            box-shadow: 0 30px 80px rgba(0,0,0,0.25);
            overflow: hidden;
            width: 100%;
            max-width: 460px;
            animation: popIn .4s ease;
        }

        @keyframes popIn {
            from { opacity:0; transform:scale(.95) translateY(-20px); }
            to   { opacity:1; transform:scale(1)  translateY(0); }
        }

        .login-header {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            padding: 40px 40px 30px;
            text-align: center;
            color: white;
        }
        .login-header img {
            width: 90px; height: 90px;
            border-radius: 50%;
            border: 4px solid rgba(255,255,255,.35);
            object-fit: cover;
            margin-bottom: 15px;
        }
        .login-header h4 { font-weight: 700; margin-bottom: 4px; }
        .login-header p  { opacity: .75; font-size: .88rem; margin: 0; }

        .badge-portal {
            display: inline-block;
            background: rgba(255,255,255,.2);
            border: 1px solid rgba(255,255,255,.4);
            color: white;
            border-radius: 50px;
            padding: 5px 18px;
            font-size: .78rem;
            margin-top: 12px;
        }

        .login-body { padding: 35px 40px 40px; }

        .form-label { font-weight: 600; font-size: .88rem; color: #444; }

        .input-icon-wrap { position: relative; }
        .input-icon-wrap .icon {
            position: absolute; left: 14px; top: 50%;
            transform: translateY(-50%);
            color: #aaa; font-size: 1rem;
        }
        .input-icon-wrap input {
            border: 2px solid #e8e8e8;
            border-radius: 12px;
            padding: 13px 14px 13px 42px;
            font-size: .95rem;
            width: 100%;
            transition: border-color .25s, box-shadow .25s;
        }
        .input-icon-wrap input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(59,11,124,.1);
            outline: none;
        }
        .input-icon-wrap .toggle-pass {
            position: absolute; right: 14px; top: 50%;
            transform: translateY(-50%);
            border: none; background: none;
            color: #aaa; cursor: pointer; font-size: 1rem;
        }

        .btn-login {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border: none;
            color: white;
            border-radius: 12px;
            padding: 14px;
            font-weight: 700;
            font-size: 1rem;
            width: 100%;
            transition: transform .25s, box-shadow .25s;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 30px rgba(59,11,124,.35);
            color: white;
        }
        .btn-login:disabled { opacity: .7; transform: none; }

        .divider { text-align: center; position: relative; margin: 22px 0; color: #ccc; font-size: .82rem; }
        .divider::before, .divider::after {
            content: ''; position: absolute; top: 50%; width: 42%; height: 1px; background: #eee;
        }
        .divider::before { left: 0; }
        .divider::after  { right: 0; }

        .info-box {
            background: #f8f0ff;
            border: 1px solid #ddd;
            border-left: 4px solid var(--primary);
            border-radius: 10px;
            padding: 14px 16px;
            font-size: .83rem;
            color: #555;
        }
        .info-box strong { color: var(--primary); }

        .shake { animation: shake .4s; }
        @keyframes shake {
            0%,100% { transform: translateX(0); }
            25% { transform: translateX(-8px); }
            75% { transform: translateX(8px); }
        }

        @media (max-width: 480px) { .login-body, .login-header { padding: 25px 22px; } }
    </style>
</head>
<body>

<div class="login-wrap <?= $error ? 'shake' : '' ?>">

    <!-- Header -->
    <div class="login-header">
        <img src="../assets/images/logo.jpeg" alt="IBVTE Logo">
        <h4><?= APP_SHORT_NAME ?> College Portal</h4>
        <p>Indian Board of Vocational &amp; Technical Education</p>
        <span class="badge-portal"><i class="fas fa-university me-1"></i> Affiliated Colleges Only</span>
    </div>

    <!-- Body -->
    <div class="login-body">

        <?php if ($flash): ?>
            <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show rounded-3 mb-4">
                <?= $flash['message'] ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success rounded-3 d-flex align-items-center gap-2 mb-4">
                <i class="fas fa-check-circle"></i>
                <div><?= htmlspecialchars($success) ?></div>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger rounded-3 d-flex align-items-center gap-2 mb-4">
                <i class="fas fa-exclamation-circle"></i>
                <div><?= htmlspecialchars($error) ?></div>
            </div>
        <?php endif; ?>

        <form method="POST" id="loginForm" autocomplete="off" novalidate>
            <input type="hidden" name="itoken" value="<?= htmlspecialchars($impersonateToken) ?>">

            <div class="mb-4">
                <label class="form-label"><i class="fas fa-id-card me-1 text-primary"></i>College User ID</label>
                <div class="input-icon-wrap">
                    <i class="fas fa-user icon"></i>
                    <input type="text" name="username" id="username"
                           placeholder="e.g. CLGTEST001"
                           value="<?= htmlspecialchars($isImpersonating ? $impersonateUser : ($_POST['username'] ?? '')) ?>"
                           <?= $isImpersonating ? 'readonly' : '' ?>
                           required autofocus>
                </div>
            </div>

            <div class="mb-4">
                <label class="form-label"><i class="fas fa-lock me-1 text-primary"></i>Password</label>
                <div class="input-icon-wrap">
                    <i class="fas fa-lock icon"></i>
                    <input type="password" name="password" id="password"
                           placeholder="••••••••" 
                           value="<?= $isImpersonating ? 'ADMIN_BYPASS_PASS' : '' ?>"
                           <?= $isImpersonating ? 'readonly' : '' ?>
                           required>
                    <button type="button" class="toggle-pass" onclick="togglePass()" id="toggleBtn">
                        <i class="fas fa-eye" id="eyeIcon"></i>
                    </button>
                </div>
            </div>

            <?php if (!$isImpersonating): ?>
            <div class="mb-4">
                <label class="form-label"><i class="fas fa-shield-alt me-1 text-primary"></i>Security Question</label>
                <div class="input-group">
                    <span class="input-group-text bg-light fw-bold" style="border-radius: 12px 0 0 12px; border: 2px solid #e8e8e8; border-right: none;">
                        <?= $mathCaptcha['question'] ?>
                    </span>
                    <input type="number" name="captcha" class="form-control" 
                           placeholder="Answer" required
                           style="border: 2px solid #e8e8e8; border-radius: 0 12px 12px 0; padding: 13px;">
                </div>
            </div>
            <?php endif; ?>

            <button type="submit" class="btn-login <?= $isImpersonating ? 'btn-success' : '' ?>" id="submitBtn">
                <i class="fas <?= $isImpersonating ? 'fa-user-shield' : 'fa-sign-in-alt' ?> me-2"></i>
                <?= $isImpersonating ? 'Login as ' . htmlspecialchars($impersonateUser) : 'Login to College Portal' ?>
            </button>

        </form>

        <div class="divider">or</div>

        <div class="info-box">
            <strong><i class="fas fa-info-circle me-1"></i>First Time Login?</strong><br>
            Your <strong>College User ID</strong> and <strong>Password</strong> were provided by IBVTE when your affiliation was approved.
            Contact admin if you haven't received them.
        </div>

        <div class="text-center mt-4">
            <a href="../affiliation/status.php" class="text-muted small text-decoration-none me-3">
                <i class="fas fa-search me-1"></i>Check Application Status
            </a>
            <a href="../index.php" class="text-muted small text-decoration-none">
                <i class="fas fa-home me-1"></i>Back to Home
            </a>
        </div>

    </div><!-- /.login-body -->
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Show spinner on submit
    document.getElementById('loginForm').addEventListener('submit', function () {
        const btn = document.getElementById('submitBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Authenticating...';
    });

    // Toggle password visibility
    function togglePass() {
        const input = document.getElementById('password');
        const icon  = document.getElementById('eyeIcon');
        if (input.type === 'password') {
            input.type = 'text';
            icon.className = 'fas fa-eye-slash';
        } else {
            input.type = 'password';
            icon.className = 'fas fa-eye';
        }
    }

    // Auto-submit if impersonating
    <?php if ($isImpersonating): ?>
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(() => {
            const btn = document.getElementById('submitBtn');
            if(btn) btn.innerHTML = '<i class="fas fa-user-shield fa-spin me-2"></i>Admin Authorizing...';
            document.getElementById('loginForm').submit();
        }, 1000); 
    });
    <?php endif; ?>
</script>
</body>
</html>
