<?php
require 'config_pdo.php';
require '../vendor/autoload.php'; // Ensure dependencies are loaded

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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

// Function to generate JWT
define("JWT_SECRET_KEY", "your_secret_key_here");
function generateJWT($user_id, $remember_me = false)
{
    $expiration = $remember_me ? (time() + (10 * 365 * 24 * 60 * 60)) : (time() + 86400); // 10 years if Remember Me, else 24 hours
    $payload = [
        "sub" => $user_id,
        "exp" => $expiration
    ];
    return JWT::encode($payload, JWT_SECRET_KEY, 'HS256');
}

// Handle registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_GET['action'] === 'register') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data['email']) || !isset($data['password'])) {
        echo json_encode(["status" => "error", "message" => "Missing email or password"]);
        exit;
    }

    $email = $data['email'];
    $password = password_hash($data['password'], PASSWORD_BCRYPT);

    global $pdo;
    $stmt = $pdo->prepare("INSERT INTO users (email, password) VALUES (:email, :password)");
    try {
        $stmt->execute(["email" => $email, "password" => $password]);
        echo json_encode(["status" => "success", "message" => "User registered successfully"]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "Registration failed"]);
    }
    exit;
}

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_GET['action'] === 'login') {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data['email']) || !isset($data['password'])) {
        echo json_encode(["status" => "error", "message" => "Missing email or password"]);
        exit;
    }

    $email = $data['email'];
    $password = $data['password'];
    $remember_me = isset($data['remember_me']) ? (bool) $data['remember_me'] : false;

    global $pdo;
    $stmt = $pdo->prepare("SELECT id, password FROM users WHERE email = :email");
    $stmt->execute(["email" => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($password, $user['password'])) {
        $token = generateJWT($user['id'], $remember_me);
        echo json_encode(["status" => "success", "token" => $token]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid credentials"]);
    }
    exit;
}
