<?php
// ✅ Enable error reporting for dev
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ Start session safely, before ANY output

require_once 'db.php';

// ✅ Redirect if already logged in
if (isset($_SESSION['logged_in_user'])) {
    if (isset($_GET['redirect']) && !empty($_GET['redirect'])) {
    $safeRedirect = basename($_GET['redirect']); // Prevent external redirects
    header("Location: $safeRedirect");
} else {
    header("Location: user-dashboard.php");
}
    exit;
}


$errorMessage = "";

// ✅ Fetch Branding Settings (background + logo)
$stmt = $pdo->query("SELECT background_image, logo_image FROM branding WHERE id = 1");
$branding = $stmt->fetch(PDO::FETCH_ASSOC);
$backgroundImage = $branding['background_image'] ?? '';
$logoImage = $branding['logo_image'] ?? '';

// ✅ Handle Login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $userId = trim($_POST['user_id']);
    $password = trim($_POST['password']);

    $stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user && password_verify($password, $user['edit_token'])) {


    // ✅ Make the session cookie last 1 year
    setcookie(session_name(), session_id(), [
        'expires' => time() + 31536000,
        'path' => '/',
        'secure' => isset($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax'
    ]);

    // ✅ Store login data
$_SESSION['logged_in_user'] = $userId;
$_SESSION['logged_in_user_name'] = $user['first_name'] ?? 'Your Sponsor';

session_write_close();

// ✅ Redirect to original page if available
if (!empty($_POST['redirect'])) {
    $safeRedirect = basename($_POST['redirect']); // Clean filename only
    header("Location: $safeRedirect");
} else {
    header("Location: user-dashboard.php");
}

exit;

}
 else {
        $errorMessage = "❌ Invalid User ID or Password.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">

    <style>
body {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
    <?php if (!empty($backgroundImage)): ?>
        background: url('<?= htmlspecialchars($backgroundImage); ?>') no-repeat center center fixed;
        background-size: cover;
    <?php else: ?>
        background: #f8f9fa;
    <?php endif; ?>
}

.content-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.logo-container {
    text-align: center;
    margin-bottom: 20px;
}

.logo-img {
    max-width: 150px;
}

.login-container {
    background: rgba(255, 255, 255, 0.9);
    padding: 30px;
    border-radius: 12px;
    box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.15);
    width: 100%;
    max-width: 400px;
    text-align: center;
}

.footer {
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    text-align: center;
    padding: 15px;
    font-size: 14px;
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
}
    </style>
</head>
<body>
<?php include 'google-translate-widget-front-end.php'; ?>
    <div class="content-wrapper">
        <?php if (!empty($logoImage)): ?>
            <div class="logo-container">
                <img src="<?= htmlspecialchars($logoImage); ?>" alt="Logo" class="logo-img">
            </div>
        <?php endif; ?>

        <div class="login-container">
            <h2><i class="fa fa-user-circle"></i> Login</h2>

            <?php if (!empty($errorMessage)): ?>
                <p class="error-message"> <?= htmlspecialchars($errorMessage); ?> </p>
            <?php endif; ?>

            <form method="POST">
<?php if (isset($_GET['redirect'])): ?>
    <input type="hidden" name="redirect" value="<?= htmlspecialchars($_GET['redirect']) ?>">
<?php endif; ?>

                <div class="mb-3">
                    <label for="user_id" class="form-label">User ID</label>
                    <input type="text" id="user_id" name="user_id" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                </div>
                <button type="submit" name="login" class="btn btn-primary w-100">Login</button>
            </form>

            <p class="mt-3">
                <a href="forgot.php">Forgot Password?</a>
            </p>
        </div>
    </div>

    <footer class="footer">
        &copy; <?= str_replace(['https://', 'http://', 'www.'], '', $_SERVER['HTTP_HOST']); ?>, All Rights Reserved.
    </footer>
</body>
</html>
