<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 🕒 login session italast for 3 hours (10800 seconds)
ini_set('session.gc_maxlifetime', 10800);
session_set_cookie_params(10800);

session_start();


require_once 'db.php'; // PDO connection - n ile db.con method tu

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $email = trim($_POST['email']);
    $password = $_POST['password'];

    // Validate input
    if (empty($email) || empty($password)) {
        $error = "⚠️ Please enter both email and password.";
    } else {
        try {
            // Prepare and execute PDO query
            $stmt = $conn->prepare("SELECT id, firstName, lastName, phone, password, is_admin, profile_pic FROM users WHERE email = :email");
            $stmt->bindValue(':email', $email, PDO::PARAM_STR);
            $stmt->execute();

            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                if (password_verify($password, $user['password'])) {
                    // ✅ Save user session
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['firstName'] = $user['firstName'];
                    $_SESSION['lastName'] = $user['lastName'];
                    $_SESSION['name'] = trim($user['firstName'] . ' ' . $user['lastName']);
                    $_SESSION['phone'] = $user['phone'];
                    $_SESSION['email'] = $email;
                    $_SESSION['is_admin'] = $user['is_admin'];
                    $_SESSION['profile_pic'] = $user['profile_pic'] ?: 'images/default-user.jpg';
                    $_SESSION['last_activity'] = time();

                    // ✅ Redirect to same page user came from
                    if (!empty($_SESSION['redirect_after_login'])) {
                        $redirect = $_SESSION['redirect_after_login'];
                        unset($_SESSION['redirect_after_login']);
                        header("Location: " . $redirect);
                    } else {
                        header("Location: index.php"); // default
                    }
                    exit();
                } else {
                    $error = "❌ Wrong password.";
                }
            } else {
                $error = "❌ No account found with that email.";
            }
        } catch (PDOException $e) {
            $error = "❌ Database error: " . htmlspecialchars($e->getMessage());
        }
    }
}

// ✅ Store where user came from before login
if (empty($_SESSION['user_id']) && isset($_SERVER['HTTP_REFERER'])) {
    $_SESSION['redirect_after_login'] = $_SERVER['HTTP_REFERER'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<title>Login - Taji Yetu</title>
<link href="https://fonts.googleapis.com/css2?family=Old+Standard+TT:wght@700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
<style>
body {
    font-family: 'Old Standard TT', serif;
    background: url('images/1.png') center/cover no-repeat fixed;
    margin: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    color: #fff;
}
.container {
    background: rgba(0,0,0,0.85);
    padding: 30px; border-radius: 12px;
    width: 100%; max-width: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
h2 { text-align: center; margin-bottom: 25px; }
form { display: flex; flex-direction: column; }
label { margin-bottom: 6px; }
input { padding: 10px; margin-bottom: 20px; border-radius: 6px; border: none; }
input:focus { outline: none; box-shadow: 0 0 5px #fff; }
button {
    background: #fff; color: #000; padding: 12px;
    border-radius: 8px; font-weight: bold;
    cursor: pointer; border: none;
}
button:hover { background: #ccc; }
.error { color: #ff8080; text-align: center; margin-bottom: 15px; }
a { color: #fff; }
a:hover { text-decoration: underline; }
.extra-links { text-align:center; margin-top:10px; }
</style>
</head>
<body>
<div class="container">
    <h2>Login</h2>

    <?php if (!empty($error)): ?>
      <div class="error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST" action="">
        <label for="email">Email</label>
        <input type="email" name="email" required />

        <label for="password">Password</label>
        <input type="password" name="password" required />

        <button type="submit">Login</button>
    </form>

    <div class="extra-links">
        <p><a href="forgot-password.php">Forgot Password?</a></p>
        <p>Don't have an account? <a href="register.html">Register here</a></p>
    </div>
</div>
</body>
</html>
