<?php
session_start();
include "connection.php";
include "validation.php";

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

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

try {
    $token = $_COOKIE["auth_token"] ?? "";

    if (empty($token)) {
        $response["message"] = "Token missing";
        echo json_encode($response); exit;
    }

    // Validate token
    $rs = Database::search("SELECT * FROM auth_tokens WHERE token='$token'");
    if ($rs->num_rows != 1) {
        $response["message"] = "Invalid token";
        echo json_encode($response); exit;
    }

    $row = $rs->fetch_assoc();

    // Check expiry
    if (strtotime($row["expires_at"]) < time()) {
        // Remove expired token
        Database::iud("DELETE FROM auth_tokens WHERE token='$token'");
        setcookie("auth_token", "", time() - 3600, "/", "", false, true);
        $response["message"] = "Token expired";
        echo json_encode($response); exit;
    }

    // Get user info
    $student_id = $row["student_id"];
    $userRS = Database::search("SELECT email, password FROM student WHERE id='$student_id'");
    if ($userRS->num_rows == 1) {
        $user = $userRS->fetch_assoc();
        $response["status"] = true;
        $response["message"] = "Valid token";
        $response["user"] = [
            "email" => $user["email"],
            "password" => $user["password"]
        ];
    }

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

echo json_encode($response);
exit;
