<?php
require "../config/database.php";
require "../includes/csrf.php";
require "../includes/subscription_guard.php";

header("Content-Type: application/json; charset=utf-8");

$data = json_decode(file_get_contents("php://input"), true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(["success" => false, "error" => "invalid_payload"]);
    exit;
}

$email = trim((string)($data["email"] ?? ""));
$password = (string)($data["password"] ?? "");

if ($email === "" || $password === "") {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "email_password_required"]);
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? LIMIT 1");
$stmt->execute([$email]);
$user = $stmt->fetch();

if (!$user || hash("sha256", $password) !== $user["password"]) {
    http_response_code(401);
    echo json_encode(["success" => false, "error" => "invalid_credentials"]);
    exit;
}

session_regenerate_id(true);
$_SESSION["user"] = $user;
$roleId = (int)($user["role_id"] ?? 0);

$redirect = "dashboard.php";
if ($roleId === 1) {
    $redirect = "admin.php";
} elseif ($roleId === 5) {
    $redirect = "dashboard.php";
} elseif ($roleId === 4) {
    $companyUserId = (int)($user["id"] ?? 0);
    if (!companyHasActiveSubscription($pdo, $companyUserId)) {
        $redirect = "subscription.php";
    } else {
        $redirect = "company_dashboard.php";
    }
} elseif ($roleId === 3) {
    $redirect = "agency_dashboard.php";
}

echo json_encode([
    "success" => true,
    "redirect" => $redirect,
    "csrf" => csrfToken()
]);
