<?php
/**
 * IBVTE Admin/Council Login with OTP
 */

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

// Check database connection before proceeding
if (!checkDBConnection()) {
    exit;
}
require_once __DIR__ . '/../middleware.php';

// Already logged in check — only auto-redirect if logged in as admin/super_admin
if (Auth()->isLoggedIn()) {
    if (Auth()->hasRole(['super_admin', 'admin'])) {
        header('Location: dashboard.php');
        exit;
    } else {
        // Logged in as college/student — clear their session so admin can login
        Auth()->logout();
    }
}


$error = '';
$otpRequired = false;
$contactMask = '';
$username = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = cleanInput($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $otp = $_POST['otp'] ?? null;
    
    $result = Auth()->login($username, $password, $otp, null);
    
    if ($result['success']) {
        header('Location: dashboard.php');
        exit;
    } elseif (isset($result['otp_required']) && $result['otp_required']) {
        $otpRequired = true;
        $contactMask = $result['contact_mask'] ?? '';
    } else {
        $error = $result['message'];
    }
}

$flash = getFlashMessage();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin 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-color: #3b0b7c;
            --secondary-color: #6c4ab6;
            --accent-color: #ffd700;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: 'Segoe UI', sans-serif;
        }
        .login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 80px rgba(0,0,0,0.3);
            overflow: hidden;
            max-width: 450px;
            width: 100%;
            margin: 20px;
            animation: slideIn 0.5s ease;
        }
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(-30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .login-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            padding: 40px;
            text-align: center;
            color: white;
        }
        .login-header img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            border: 4px solid rgba(255,255,255,0.3);
            margin-bottom: 15px;
        }
        .login-body {
            padding: 40px;
        }
        .form-floating {
            margin-bottom: 20px;
        }
        .form-control {
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            height: 55px;
        }
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(59,11,124,0.1);
        }
        .btn-login {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            border: none;
            border-radius: 12px;
            padding: 14px;
            font-weight: 600;
            width: 100%;
            color: white;
            font-size: 16px;
            transition: all 0.3s;
        }
        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(59,11,124,0.3);
            color: white;
        }
        .otp-section {
            background: #fff8e1;
            border: 2px solid #ffc107;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .security-badge {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255,255,255,0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.85rem;
        }
        .shake {
            animation: shake 0.5s;
        }
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
        }
    </style>
</head>
<body>
    <div class="login-container <?= $error ? 'shake' : '' ?>">
        <div class="login-header">
            <img src="../assets/images/logo.jpeg" alt="IBVTE Logo">
            <h4 class="mb-1">Council/Admin Login</h4>
            <p class="mb-0 opacity-75 small">Indian Board of Vocational & Technical Education</p>
            <div class="security-badge mt-3">
                <i class="fas fa-shield-alt"></i>
                <span>Secured with OTP</span>
            </div>
        </div>
        
        <div class="login-body">
            <?php if ($flash): ?>
                <div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show">
                    <?= $flash['message'] ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle me-2"></i><?= $error ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="loginForm">
                <div class="form-floating">
                    <input type="text" class="form-control" id="username" name="username" 
                           placeholder="Username" required value="<?= htmlspecialchars($username) ?>">
                    <label for="username"><i class="fas fa-user-shield me-2 text-primary"></i>Username</label>
                </div>
                
                <div class="form-floating">
                    <input type="password" class="form-control" id="password" name="password" 
                           placeholder="Password" required>
                    <label for="password"><i class="fas fa-lock me-2 text-primary"></i>Password</label>
                </div>
                
                <?php if ($otpRequired): ?>
                <div class="otp-section text-center">
                    <i class="fas fa-mobile-alt fa-2x text-warning mb-2"></i>
                    <h5 class="mb-1">OTP Verification</h5>
                    <p class="small text-muted mb-3">Enter code sent to <?= $contactMask ?></p>
                    <input type="text" name="otp" class="form-control text-center fs-4" 
                           maxlength="6" pattern="\d{4,6}" placeholder="Enter OTP" required autofocus>
                    <button type="button" class="btn btn-link btn-sm mt-2" onclick="resendOTP()">
                        Resend OTP
                    </button>
                </div>
                <?php endif; ?>
                
                <button type="submit" class="btn btn-login" id="submitBtn">
                    <i class="fas fa-sign-in-alt me-2"></i>
                    <?= $otpRequired ? 'Verify & Login' : 'Secure Login' ?>
                </button>
            </form>
            
            <div class="text-center mt-3">
                <a href="../login.php" class="text-muted small">
                    <i class="fas fa-arrow-left me-1"></i>Back to Main Login
                </a>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('loginForm').addEventListener('submit', function() {
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = 
                '<i class="fas fa-spinner fa-spin me-2"></i>Authenticating...';
        });
        
        function resendOTP() {
            fetch('../api/resend_otp.php')
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        alert('New OTP sent!');
                    }
                });
        }
    </script>
</body>
</html>
