<?php
require_once '/config/database.php';
require_once '/includes/functions.php';

if (isLoggedIn()) {
    redirect('user/dashboard.php');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username']);
    $password = $_POST['password'];
    
    if (empty($username)) $errors[] = 'Username is required';
    if (empty($password)) $errors[] = 'Password is required';
    
    if (empty($errors)) {
        $conn = getConnection();
        $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?");
        $stmt->bind_param("ss", $username, $username);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 0) {
            $errors[] = 'Username not found. Please check and try again.';
        } else {
            $user = $result->fetch_assoc();
            if (verifyPassword($password, $user['password'])) {
                session_unset(); session_destroy(); session_start();
                session_regenerate_id(true);
                $_SESSION['user_id']    = $user['id'];
                $_SESSION['username']   = $user['username'];
                $_SESSION['email']      = $user['email'];
                $_SESSION['status']     = $user['status'];
                $_SESSION['login_time'] = time();
                $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                
                if ($user['status'] === 'inactive') {
                    setFlash('info', 'Account not activated. Please activate your account.');
                    header('Location: user/activate.php'); exit();
                } else {
                    setFlash('success', 'Welcome back, ' . $user['username'] . '!');
                    header('Location: user/dashboard.php'); exit();
                }
            } else {
                $errors[] = 'Incorrect password. Please try again.';
            }
        }
    }
}

$themeColor = getSetting('theme_color', '#4F67F0');
$siteName   = getSiteName();
$flash      = getFlash();
$siteLogo   = getSetting('site_logo', '');
$hasCustomLogo = !empty($siteLogo) && file_exists('uploads/logos/' . $siteLogo);

function hexToRgb($hex) {
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $r = hexdec(str_repeat(substr($hex,0,1),2));
        $g = hexdec(str_repeat(substr($hex,1,1),2));
        $b = hexdec(str_repeat(substr($hex,2,1),2));
    } else {
        $r = hexdec(substr($hex,0,2));
        $g = hexdec(substr($hex,2,2));
        $b = hexdec(substr($hex,4,2));
    }
    return "$r, $g, $b";
}
$rgbColor = hexToRgb($themeColor);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sign In — <?php echo htmlspecialchars($siteName); ?></title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }

        :root {
            --accent: <?php echo $themeColor; ?>;
            --accent-rgb: <?php echo $rgbColor; ?>;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f5f5f7;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .card {
            background: #fff;
            border-radius: 16px;
            padding: 40px 36px;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.06), 0 16px 40px rgba(0,0,0,0.07);
        }

        .logo-area {
            text-align: center;
            margin-bottom: 28px;
        }

        .logo-circle {
            width: 56px;
            height: 56px;
            background: var(--accent);
            border-radius: 14px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
        }
        .logo-circle img { width: 38px; height: 38px; object-fit: contain; border-radius: 10px; }
        .logo-circle i   { font-size: 22px; color: #fff; }

        .site-title {
            font-size: 18px;
            font-weight: 600;
            color: #111;
            letter-spacing: -0.3px;
        }
        .site-sub { font-size: 13px; color: #888; margin-top: 3px; }

        .alert {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 11px 14px;
            border-radius: 10px;
            font-size: 13px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        .alert-error   { background: #fff1f1; color: #c0392b; }
        .alert-warning { background: #fffbec; color: #b07d0a; }
        .alert i       { font-size: 14px; flex-shrink: 0; }

        .field { margin-bottom: 16px; }

        .field-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 6px;
        }

        label { font-size: 13px; font-weight: 500; color: #333; display: block; margin-bottom: 6px; }
        .field-top label { margin-bottom: 0; }

        .link-small { font-size: 12px; color: var(--accent); text-decoration: none; font-weight: 500; }
        .link-small:hover { text-decoration: underline; }

        .input-wrap { position: relative; }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            height: 44px;
            padding: 0 40px 0 13px;
            border: 1.5px solid #e5e5e5;
            border-radius: 10px;
            font-family: 'Inter', sans-serif;
            font-size: 14px;
            color: #111;
            background: #fff;
            outline: none;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        input:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(var(--accent-rgb), 0.1);
        }
        input.err { border-color: #e74c3c; }
        input::placeholder { color: #bbb; }

        .toggle-pwd {
            position: absolute;
            right: 12px; top: 50%;
            transform: translateY(-50%);
            background: none; border: none;
            cursor: pointer; color: #aaa;
            font-size: 14px; padding: 2px;
            transition: color 0.2s;
        }
        .toggle-pwd:hover { color: var(--accent); }

        .remember {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 4px 0 20px;
        }
        .remember input { width: 15px; height: 15px; accent-color: var(--accent); cursor: pointer; }
        .remember label { font-size: 13px; color: #666; cursor: pointer; user-select: none; font-weight: 400; margin: 0; }

        .btn {
            width: 100%; height: 46px;
            background: var(--accent);
            color: #fff; border: none;
            border-radius: 10px;
            font-family: 'Inter', sans-serif;
            font-size: 14px; font-weight: 600;
            cursor: pointer;
            display: flex; align-items: center; justify-content: center; gap: 8px;
            transition: opacity 0.2s, transform 0.15s, box-shadow 0.2s;
            box-shadow: 0 4px 14px rgba(var(--accent-rgb), 0.3);
        }
        .btn:hover:not(:disabled) {
            opacity: 0.9;
            transform: translateY(-1px);
            box-shadow: 0 6px 18px rgba(var(--accent-rgb), 0.35);
        }
        .btn:active:not(:disabled) { transform: translateY(0); }
        .btn:disabled { opacity: 0.6; cursor: not-allowed; }

        .spinner {
            display: none;
            width: 16px; height: 16px;
            border: 2px solid rgba(255,255,255,0.35);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }
        .btn.loading .btn-text { display: none; }
        .btn.loading .spinner  { display: block; }
        @keyframes spin { to { transform: rotate(360deg); } }

        .divider {
            display: flex; align-items: center;
            gap: 12px; margin: 22px 0;
        }
        .divider-line { flex: 1; height: 1px; background: #ebebeb; }
        .divider-text { font-size: 12px; color: #bbb; }

        .social-row { display: flex; gap: 10px; }
        .social-btn {
            flex: 1; height: 40px;
            border: 1.5px solid #e5e5e5;
            border-radius: 10px;
            background: #fff;
            display: flex; align-items: center; justify-content: center;
            color: #555; font-size: 15px;
            cursor: pointer; text-decoration: none;
            transition: border-color 0.2s, color 0.2s;
        }
        .social-btn:hover { border-color: var(--accent); color: var(--accent); }

        .card-footer {
            text-align: center;
            margin-top: 22px;
            font-size: 13px; color: #888;
        }
        .card-footer a { color: var(--accent); text-decoration: none; font-weight: 500; }
        .card-footer a:hover { text-decoration: underline; }

        @media (max-width: 440px) {
            .card { padding: 32px 24px; }
        }

        @media (prefers-reduced-motion: reduce) {
            * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
        }
    </style>
</head>
<body>

<div class="card">

    <div class="logo-area">
        <div class="logo-circle">
            <?php if ($hasCustomLogo): ?>
                <img src="uploads/logos/<?php echo htmlspecialchars($siteLogo); ?>" alt="<?php echo htmlspecialchars($siteName); ?>">
            <?php else: ?>
                <i class="fas fa-bolt"></i>
            <?php endif; ?>
        </div>
        <div class="site-title"><?php echo htmlspecialchars($siteName); ?></div>
        <div class="site-sub">Sign in to your account</div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error" role="alert">
            <i class="fas fa-circle-exclamation"></i>
            <?php echo htmlspecialchars($errors[0]); ?>
        </div>
    <?php endif; ?>

    <?php if ($flash && $flash['type'] === 'warning'): ?>
        <div class="alert alert-warning" role="alert">
            <i class="fas fa-triangle-exclamation"></i>
            <?php echo htmlspecialchars($flash['message']); ?>
        </div>
    <?php endif; ?>

    <form method="POST" id="loginForm" novalidate>

        <div class="field">
            <label for="username">Username</label>
            <div class="input-wrap">
                <input type="text" id="username" name="username"
                    class="<?php echo (!empty($errors) && strpos($errors[0],'not found')!==false) ? 'err' : ''; ?>"
                    value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>"
                    placeholder="Enter your username"
                    autocomplete="username" aria-required="true">
            </div>
        </div>

        <div class="field">
            <div class="field-top">
                <label for="password">Password</label>
                <a href="forgot-password.php" class="link-small">Forgot password?</a>
            </div>
            <div class="input-wrap">
                <input type="password" id="password" name="password"
                    class="<?php echo (!empty($errors) && strpos($errors[0],'password')!==false) ? 'err' : ''; ?>"
                    placeholder="••••••••"
                    autocomplete="current-password" aria-required="true">
                <button type="button" class="toggle-pwd" id="togglePwd" aria-label="Show password">
                    <i class="fa-regular fa-eye-slash" id="eyeIcon"></i>
                </button>
            </div>
        </div>

        <div class="remember">
            <input type="checkbox" id="remember" name="remember">
            <label for="remember">Remember me</label>
        </div>

        <button type="submit" class="btn" id="loginBtn">
            <span class="btn-text">Sign In</span>
            <div class="spinner"></div>
        </button>

    </form>

    <div class="divider">
        <span class="divider-line"></span>
        <span class="divider-text">or</span>
        <span class="divider-line"></span>
    </div>

    <div class="social-row">
        <a href="#" class="social-btn" aria-label="Facebook"><i class="fab fa-facebook-f"></i></a>
        <a href="#" class="social-btn" aria-label="X / Twitter"><i class="fab fa-x-twitter"></i></a>
        <a href="#" class="social-btn" aria-label="Instagram"><i class="fab fa-instagram"></i></a>
    </div>

    <div class="card-footer">
        Don't have an account? <a href="register.php">Sign Up</a>
    </div>

</div>

<script>
(function(){
    document.getElementById('togglePwd').addEventListener('click', function(){
        var p = document.getElementById('password');
        var i = document.getElementById('eyeIcon');
        var show = p.type === 'password';
        p.type = show ? 'text' : 'password';
        i.className = show ? 'fa-regular fa-eye' : 'fa-regular fa-eye-slash';
        this.setAttribute('aria-label', show ? 'Hide password' : 'Show password');
    });

    document.getElementById('loginForm').addEventListener('submit', function(e){
        var u = document.getElementById('username').value.trim();
        var p = document.getElementById('password').value.trim();
        if (!u || !p) { e.preventDefault(); return; }
        var btn = document.getElementById('loginBtn');
        btn.classList.add('loading');
        btn.disabled = true;
    });

    var err = document.querySelector('input.err');
    if (err) err.focus();
}());
</script>

</body>
</html>