<?php
require_once '../includes/session.php';
require_once '../includes/db.php';

// ==========================
// VALIDATE TOKEN
// ==========================
$token = $_GET['token'] ?? '';

if (empty($token)) {
    die("Invalid login link.");
}

// ==========================
// FETCH TOKEN
// ==========================
$stmt = $conn->prepare("
    SELECT t.*, u.id AS user_id, u.first_name, u.last_name
    FROM auto_login_tokens t
    JOIN users u ON t.user_id = u.id
    WHERE t.token = ? AND t.used = 0
    LIMIT 1
");
$stmt->bind_param("s", $token);
$stmt->execute();

$result = $stmt->get_result();
$data = $result->fetch_assoc();

if (!$data) {
    // Token invalid or already used: redirect to login page
    header("Location: ../auth/login.php");
    exit;
}

// ==========================
// CHECK EXPIRY
// ==========================
$currentTime = time();
$expiryTime = strtotime($data['expires_at']);

if ($currentTime > $expiryTime) {
    // Token expired: redirect to login page
    header("Location: ../auth/login.php");
    exit;
}

// ==========================
// LOGIN USER
// ==========================
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['user_name'] = $data['first_name'] . ' ' . $data['last_name'];

// ==========================
// MARK TOKEN AS USED
// ==========================
$update = $conn->prepare("UPDATE auto_login_tokens SET used = 1 WHERE id = ?");
$update->bind_param("i", $data['id']);
$update->execute();

// ==========================
// OPTIONAL: LOG EVENT
// ==========================
$log = $conn->prepare("
    INSERT INTO security_logs (type, message)
    VALUES ('auto_login', ?)
");

$msg = "User ID {$data['user_id']} logged in via auto-login link";
$log->bind_param("s", $msg);
$log->execute();

// ==========================
// REDIRECT
// ==========================
header("Location: ../user/dashboard.php");
exit;