<?php
require_once 'functions.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Treat this input as a general login identifier (could be email or account number)
    $login_identifier = trim($_POST['login_identifier'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($login_identifier) || empty($password)) {
        $error = 'Please enter both your email/account number and password.';
    } else {
        $db = getDB();
        
        // Check both the email and account_number columns for a match
        $stmt = $db->prepare("SELECT * FROM users WHERE email = ? OR account_number = ?");
        $stmt->bind_param('ss', $login_identifier, $login_identifier);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();
            
            if (isLockedOut($user)) {
                $error = 'Account is temporarily locked. Please try again later.';
            } elseif (verifyPassword($password, $user['password'])) {
                // Check if login OTP is enabled
                if ($user['enable_otp_login']) {
                    $_SESSION['otp_user_id'] = $user['id'];
                    $_SESSION['otp_email'] = $user['email'];
                    $_SESSION['otp_code'] = generateOTP();
                    $_SESSION['otp_purpose'] = 'login';
                    
                    // Send OTP email
                    $otpBody = "Your Flexi Access login verification code is: <strong>" . $_SESSION['otp_code'] . "</strong><br><br>This code will expire in 10 minutes.";
                    @sendMail($user['email'], 'Login Verification Code', $otpBody);
                    
                    header('Location: verify-otp.php');
                    exit();
                }
                
                // Log login
                logLogin($user['id'], 'user', 'success');
                
                // Reset login attempts
                $stmt = $db->prepare("UPDATE users SET login_attempts = 0, last_login = NOW(), last_login_ip = ? WHERE id = ?");
                $ip = $_SERVER['REMOTE_ADDR'];
                $stmt->bind_param('si', $ip, $user['id']);
                $stmt->execute();
                
                // Set session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_type'] = 'user';
                $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
                
                createNotification($user['id'], 'Login Successful', 'You have successfully logged in to your account.', 'success');
                
                header('Location: dashboard.php');
                exit();
            } else {
                // Increment login attempts
                $attempts = ($user['login_attempts'] ?? 0) + 1;
                $lockedUntil = null;
                
                if ($attempts >= MAX_LOGIN_ATTEMPTS) {
                    $lockedUntil = date('Y-m-d H:i:s', time() + LOCKOUT_DURATION);
                }
                
                $stmt = $db->prepare("UPDATE users SET login_attempts = ?, locked_until = ? WHERE id = ?");
                $stmt->bind_param('isi', $attempts, $lockedUntil, $user['id']);
                $stmt->execute();
                
                logLogin($user['id'], 'user', 'failed');
                
                $remaining = MAX_LOGIN_ATTEMPTS - $attempts;
                $error = "Invalid password. {$remaining} attempts remaining.";
            }
        } else {
            $error = 'Invalid email/account number or password.';
        }
    }
}

// Function helper to dynamically query the 'settings' table structure safely
function getSettingValue($key, $default = '') {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT `value` FROM `settings` WHERE `key` = ? LIMIT 1");
        $stmt->bind_param('s', $key);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && $res->num_rows > 0) {
            $row = $res->fetch_assoc();
            return !empty(trim($row['value'])) ? trim($row['value']) : $default;
        }
    } catch (Exception $e) {
        // Fallback gracefully if database connection isn't configured
    }
    return $default;
}

// Dynamic pulls from SQL table
$dbSiteName   = getSettingValue('site_name', defined('SITE_NAME') ? SITE_NAME : 'Flexi Access');
$dbSiteTagline= getSettingValue('site_tagline', defined('SITE_TAGLINE') ? SITE_TAGLINE : '');
$dbFaviconUrl = getSettingValue('site_favicon', 'assets/images/logo.png');
$dbLogoUrl    = getSettingValue('site_logo', 'assets/images/logo.png');
$tawkScript   = getSettingValue('tawk_livechat_script', ''); // Pulls the full script snippet if saved directly inside database row
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Login - <?php echo htmlspecialchars($dbSiteName); ?></title>
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($dbFaviconUrl); ?>">
    <link rel="shortcut icon" type="image/x-icon" href="<?php echo htmlspecialchars($dbFaviconUrl); ?>">
    
    <link rel="stylesheet" href="assets/css/style.css">

    <style type="text/css">
        html, body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            min-height: 100vh;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }
        *, *:before, *:after {
            box-sizing: inherit;
        }
        body.login-page {
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%); 
            padding: 24px;
        }
        .login-container {
            width: 100%;
            max-width: 480px; /* Perfectly structured desktop display width */
            margin: auto;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }
        .login-card {
            background: #ffffff;
            border-radius: 16px;
            padding: 40px 36px;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.05);
            width: 100%;
        }
        .login-logo img {
            max-width: 200px;
            height: auto;
            display: block;
            margin: 0 auto 16px auto;
        }
        .login-logo p {
            text-align: center;
            color: #6b7280;
            font-size: 14px;
            margin: 0 0 28px 0;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            font-size: 14px;
            color: #374151;
        }
        .form-control {
            width: 100%;
            display: block;
            padding: 12px 14px;
            border-radius: 8px;
            border: 1px solid #d1d5db;
            font-size: 15px;
            background-color: #fff;
            transition: border-color 0.15s ease;
        }
        .form-control:focus {
            outline: none;
            border-color: #2563eb;
        }
        .btn-block {
            width: 100%;
            display: block;
            border: none;
            border-radius: 8px;
            background-color: #2563eb;
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.15s ease;
        }
        .btn-block:hover {
            background-color: #1d4ed8;
        }
        
        /* Desktop 5 & Large Screen Structural Rule overrides */
        @media (min-width: 1440px) {
            .login-container {
                max-width: 520px; /* Slight scaling enhancement for wider presentation panels */
            }
            .login-card {
                padding: 48px 44px;
            }
        }

        /* Mobile Layout Rule overrides */
        @media (max-width: 480px) {
            body.login-page {
                padding: 16px;
                align-items: flex-start;
            }
            .login-card {
                padding: 28px 20px;
                border-radius: 12px;
            }
        }
    </style>
</head>
<body class="login-page">
    <div class="login-container">
        <div class="login-card">
            <div class="login-logo">
                <img src="<?php echo htmlspecialchars($dbLogoUrl); ?>" alt="<?php echo htmlspecialchars($dbSiteName); ?>">
                <p><?php echo htmlspecialchars($dbSiteTagline); ?></p>
            </div>
            
            <?php if (!empty($error)): ?>
                <div class="alert alert-danger" style="margin-bottom: 20px; padding: 12px; background: #fee2e2; color: #991b1b; border-radius: 8px; font-size: 14px;">
                    <span>⚠</span> <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label">Email Address or Account Number</label>
                    <input type="text" name="login_identifier" class="form-control" placeholder="Enter email or account number" value="<?php echo isset($_POST['login_identifier']) ? htmlspecialchars($_POST['login_identifier']) : ''; ?>" required autofocus>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <div style="position: relative;">
                        <input type="password" name="password" id="login-password" class="form-control" placeholder="Enter your password" required>
                        <button type="button" onclick="togglePassword('login-password', this)" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #9ca3af; font-size: 16px;">👁️‍🗨️</button>
                    </div>
                </div>
                
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
                    <label style="display: flex; align-items: center; gap: 6px; font-size: 13px; color: #4b5563; cursor: pointer; user-select: none;">
                        <input type="checkbox" name="remember" style="accent-color: #2563eb;"> Remember me
                    </label>
                    <a href="forgot-password.php" style="font-size: 13px; color: #2563eb; font-weight: 600; text-decoration: none;">Forgot Password?</a>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block" style="padding: 14px;">
                    Sign In
                </button>
            </form>
            
            <div style="text-align: center; margin-top: 24px; padding-top: 24px; border-top: 1px solid #e5e7eb;">
                <p style="font-size: 14px; color: #4b5563; margin: 0;">
                    Don't have an account? <a href="register.php" style="color: #2563eb; font-weight: 700; text-decoration: none;">Get Started</a>
                </p>
            </div>
        </div>
        
        <p style="text-align: center; margin-top: 12px; font-size: 12px; color: #6b7280; line-height: 1.5;">
            &copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($dbSiteName); ?>. All rights reserved. <br>
            Secured with 256-bit SSL encryption.
        </p>
    </div>
    
    <script src="assets/js/main.js"></script>

    <?php if (!empty($tawkScript)): ?>
        <?php echo $tawkScript; ?>
    <?php else: ?>
        <script type="text/javascript">
        var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
        (function(){
            var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
            s1.async = true;
            s1.src = 'https://embed.tawk.to/66f75c544cbc4814f7e034cf/1i8r41aru';
            s1.charset = 'UTF-8';
            s1.setAttribute('crossorigin', '*');
            s0.parentNode.insertBefore(s1, s0);
        })();
        </script>
    <?php endif; ?>
</body>
</html>
