<?php

declare(strict_types=1);

require_once "../db.php";
require_once "./customer_auth_common.php";

error_reporting(E_ERROR | E_PARSE);
ini_set("display_errors", "0");

if (($_SERVER["REQUEST_METHOD"] ?? "") !== "POST") {
    customerAuthJsonResponse(405, [
        "success" => false,
        "message" => "Method not allowed",
    ]);
}

$input = customerAuthReadJsonInput();
$email = strtolower(customerAuthGetInputValue($input, "email"));
$password = customerAuthGetInputValue($input, "password");

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    customerAuthJsonResponse(422, [
        "success" => false,
        "message" => "Please enter a valid email address.",
    ]);
}

if ($password === "") {
    customerAuthJsonResponse(422, [
        "success" => false,
        "message" => "Password is required.",
    ]);
}

$userStmt = $conn->prepare(
    "SELECT id, name, email, password, role
     FROM users
     WHERE email = ?
     LIMIT 1"
);

if (!$userStmt) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Failed to prepare user lookup.",
    ]);
}

$userStmt->bind_param("s", $email);
$userStmt->execute();
$result = $userStmt->get_result();
$user = $result ? $result->fetch_assoc() : null;
$userStmt->close();

if (!$user) {
    customerAuthJsonResponse(401, [
        "success" => false,
        "message" => "Invalid email or password.",
    ]);
}

$storedPasswordHash = (string) ($user["password"] ?? "");
if ($storedPasswordHash === "" || !password_verify($password, $storedPasswordHash)) {
    customerAuthJsonResponse(401, [
        "success" => false,
        "message" => "Invalid email or password.",
    ]);
}

$userId = (int) ($user["id"] ?? 0);
$userName = trim((string) ($user["name"] ?? ""));
$userRole = trim((string) ($user["role"] ?? "user"));
if ($userName === "") {
    $userName = strstr($email, "@", true) ?: "User";
}
if ($userRole === "") {
    $userRole = "user";
}

if (password_needs_rehash($storedPasswordHash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($password, PASSWORD_DEFAULT);
    $rehashStmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    if ($rehashStmt) {
        $rehashStmt->bind_param("si", $newHash, $userId);
        $rehashStmt->execute();
        $rehashStmt->close();
    }
}

try {
    $session = customerAuthCreateSession($conn, $userId);
} catch (RuntimeException $exception) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Unable to create login session.",
    ]);
}

customerAuthJsonResponse(200, [
    "success" => true,
    "message" => "Login successful.",
    "token" => $session["token"],
    "expiresAt" => $session["expiresAt"],
    "expiresInSeconds" => $session["expiresInSeconds"],
    "user" => [
        "id" => $userId,
        "name" => $userName,
        "email" => $email,
        "role" => $userRole,
    ],
]);
