<?php
ob_start();
session_start();

include "connection.php";
include "validation.php";

ob_clean();
header("Content-Type: application/json");

$response = ["status" => false, "message" => ""];

try {

    $json = file_get_contents("php://input");
    $data = json_decode($json, true);

    if (!$data) {
        $response["message"] = "Invalid request data.";
        echo json_encode($response);
        exit;
    }

    $email = trim($data["email"] ?? "");
    $password = trim($data["password"] ?? "");
    $remember = $data["remember"] ?? false; // ⭐ ADDED

    if (empty($email)) {
        $response["message"] = "Please Enter Email Address";
        echo json_encode($response);
        exit;
    }

    if (empty($password)) {
        $response["message"] = "Please Enter Password";
        echo json_encode($response);
        exit;
    }

    if (!isValidEmail($email)) {
        $response["message"] = "Please enter a valid email address";
        echo json_encode($response);
        exit;
    }

    // Login check
    $rs = Database::search("SELECT * FROM `student` WHERE `email`='$email' AND `password`='$password'");
    if ($rs->num_rows != 1) {
        $response["message"] = "Invalid email or password.";
        echo json_encode($response);
        exit;
    }

    $user = $rs->fetch_assoc();

    if ($user["student_status_id"] == 3) {
        $response["message"] = "Your account is suspended!";
        echo json_encode($response);
        exit;
    }

    $student_id = $user["id"];

    // ⭐ Store full user in session
    $_SESSION["user"] = $user;

    // ⭐ Always remove OLD tokens (prevent 2 device login)
    Database::iud("DELETE FROM auth_tokens WHERE student_id='$student_id'");

    // IF REMEMBER ME = FALSE → do not create a token
    if (!$remember) {

        // ✔ Remove cookie if exists
        setcookie("auth_token", "", time() - 3600, "/", "", false, true);

        $response["status"] = true;
        $response["message"] = "Login successful (no remember me)";
        $response["token"] = null;
        echo json_encode($response);
        exit;
    }

    // ⭐ Remember Me = TRUE → Create Token
    $token = bin2hex(random_bytes(32));
    $expires = date("Y-m-d H:i:s", time() + (30 * 24 * 60 * 60));

    $d = new DateTime();
    $tz = new DateTimeZone("Asia/Colombo");
    $d->setTimezone($tz);
    $created = $d->format("Y-m-d H:i:s");

    Database::iud("INSERT INTO auth_tokens (student_id, token, created_at, expires_at) 
                   VALUES ('$student_id', '$token', '$created', '$expires')");

    // Save token cookie
    setcookie(
        "auth_token",
        $token,
        time() + (30 * 24 * 60 * 60),
        "/",
        "",
        false,
        true
    );

    $response["status"] = true;
    $response["message"] = "Login successful!";
    $response["token"] = $token;

} catch (Exception $e) {
    $response["message"] = $e->getMessage();
}

echo json_encode($response);
exit;
