<?php
define('SECURE_ACCESS', true);

$pageTitle = "Login";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

redirectIfLoggedIn();

$error = '';
$dbConfigured = ($pdo !== null);

$configs = [];
try {
    if ($dbConfigured) {
        $stmt_c = $pdo->query("SELECT key, value FROM system_settings");
        $configs = $stmt_c->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    }
} catch (PDOException $e) {
    // Ignore
}
$logo_url = !empty($configs['site_logo']) ? $configs['site_logo'] : 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=100&auto=format&fit=crop';
$site_name = !empty($configs['site_name']) ? $configs['site_name'] : 'EventPortal';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $dbConfigured) {
    $loginInput = trim($_POST['login_input'] ?? '');
    $password = $_POST['password'] ?? '';

    if (empty($loginInput) || empty($password)) {
        $error = "Please fill in all fields.";
    } else {
        try {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR phone = ?");
            $stmt->execute([$loginInput, $loginInput]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                if ($user['status'] !== 'active') {
                    $error = "Your account is currently inactive. Please contact an admin.";
                } elseif (isset($user['is_email_verified']) && !$user['is_email_verified'] && ($configs['require_email_verification'] ?? '1') === '1' && $user['role'] !== 'admin') {
                    $error = "Please verify your email address before logging in. Check your inbox for the verification link.";
                } elseif (isset($user['is_2fa_enabled']) && $user['is_2fa_enabled']) {
                    // Trigger 2FA
                    $code = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
                    $expires = date('Y-m-d H:i:s', strtotime('+15 minutes'));
                    
                    $upd = $pdo->prepare("UPDATE users SET two_factor_code = ?, two_factor_expires = ? WHERE id = ?");
                    $upd->execute([$code, $expires, $user['id']]);

                    require_once __DIR__ . '/../includes/notification_helper.php';
                    sendMultichannelNotification($user['id'], '2fa_code', [
                        'username' => $user['username'],
                        'code' => $code
                    ]);

                    if (session_status() === PHP_SESSION_NONE) {
                        session_start();
                    }
                    $_SESSION['2fa_pending_user_id'] = $user['id'];
                    $_SESSION['2fa_redirect'] = trim($_GET['redirect'] ?? '');
                    
                    header("Location: verify_2fa");
                    exit();
                } else {
                    // Populate session
                    session_regenerate_id(true);
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['username'] = $user['username'];
                    $_SESSION['email'] = $user['email'];
                    $_SESSION['role'] = $user['role'];
                    $_SESSION['status'] = $user['status'];
                    
                    $redirect = trim($_GET['redirect'] ?? '');
                    if (!empty($redirect) && preg_match('/^[a-z0-9_\-\.\/]+\.php(\?[a-z0-9_&=\-\.\/\%]*)?$/i', $redirect)) {
                        header("Location: " . $redirect);
                    } else {
                        header("Location: dashboard");
                    }
                    exit();
                }
            } else {
                $error = "Invalid email/phone number or password.";
            }
        } catch (PDOException $e) {
            $error = "Database 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>RENENET EDUCARE</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        html {
            font-size: 16px;
        }
        @media (max-width: 576px) {
            html { font-size: 14px; }
        }
        body {
            font-size: calc(14px + 0.2vw);
            background-color: #f8f9fa;
        }
        .login-card {
            border: none;
            border-radius: 12px;
        }
    </style>
</head>
<body class="d-flex align-items-center min-vh-100 py-4">
    <div class="container-fluid px-md-5">
        <div class="row justify-content-center">
            <div class="col-12 col-sm-10 col-md-8 col-lg-6 col-xl-5">
                
                <?php if (!$dbConfigured): ?>
                    <div class="alert alert-warning shadow-sm border-0 mb-4" role="alert">
                        <h5 class="alert-heading"><i class="bi bi-exclamation-triangle-fill me-2"></i>Database Not Setup</h5>
                        <p class="mb-2">The application could not connect to the database <strong><?php echo DB_NAME; ?></strong>. You must initialize it before you can log in.</p>
                        <a href="setup" class="btn btn-warning btn-sm fw-bold">Run Database Setup Now</a>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['flash_error'])): ?>
                    <div class="alert alert-danger shadow-sm border-0 mb-4" role="alert">
                        <i class="bi bi-exclamation-circle-fill me-2"></i>
                        <?php echo htmlspecialchars($_SESSION['flash_error']); ?>
                        <?php unset($_SESSION['flash_error']); ?>
                    </div>
                <?php endif; ?>

                <?php if (isset($_SESSION['flash_success'])): ?>
                    <div class="alert alert-success shadow-sm border-0 mb-4" role="alert">
                        <i class="bi bi-check-circle-fill me-2"></i>
                        <?php echo htmlspecialchars($_SESSION['flash_success']); ?>
                        <?php unset($_SESSION['flash_success']); ?>
                    </div>
                <?php endif; ?>

                <div class="card shadow-lg login-card p-4">
                    <div class="card-body">
                        <div class="text-center mb-4">
                            <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="mb-3" style="max-width: 220px; max-height: 80px; object-fit: contain;">
                            <h2 class="fw-bold"><?php echo htmlspecialchars($site_name); ?></h2>
                            <p class="text-muted">Enter credentials to access your event dashboard</p>
                        </div>

                        <?php if (!empty($error)): ?>
                            <div class="alert alert-danger shadow-sm border-0 mb-3" role="alert">
                                <i class="bi bi-x-circle-fill me-2"></i>
                                <?php echo htmlspecialchars($error); ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="login?redirect=<?php echo urlencode($_GET['redirect'] ?? ''); ?>" class="needs-validation" novalidate>
                            <div class="mb-3">
                                <label for="login_input" class="form-label">Email or Phone Number</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-person-fill"></i></span>
                                    <input type="text" class="form-control border-start-0 ps-0" id="login_input" name="login_input" required placeholder="e.g. user@example.com or +919876543200" <?php echo !$dbConfigured ? 'disabled' : ''; ?>>
                                </div>
                            </div>

                            <div class="mb-4">
                                <div class="d-flex justify-content-between align-items-center">
                                    <label for="password" class="form-label mb-1">Password</label>
                                    <a href="forgot_password" class="small text-decoration-none">Forgot Password?</a>
                                </div>
                                <div class="input-group">
                                    <span class="input-group-text bg-white text-muted border-end-0"><i class="bi bi-lock-fill"></i></span>
                                    <input type="password" class="form-control border-start-0 ps-0" id="password" name="password" required placeholder="••••••••" <?php echo !$dbConfigured ? 'disabled' : ''; ?>>
                                </div>
                            </div>

                            <div class="d-grid gap-2 mb-4">
                                <button type="submit" class="btn btn-primary btn-lg py-2" <?php echo !$dbConfigured ? 'disabled' : ''; ?>>
                                    <i class="bi bi-box-arrow-in-right me-2"></i>Log In
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
