<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/csrf.php";
require_once "../includes/lang.php";

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

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
    exit;
}

$payload = json_decode(file_get_contents("php://input"), true) ?: [];
if (!requireCsrfFromPayload($payload, "csrf")) {
    http_response_code(419);
    echo json_encode(["success" => false, "error" => "csrf_failed"]);
    exit;
}

$currentPassword = (string)($payload["current_password"] ?? "");
$newPassword = (string)($payload["new_password"] ?? "");
$confirmPassword = (string)($payload["confirm_password"] ?? "");
$userId = (int)($_SESSION["user"]["id"] ?? 0);

if ($userId <= 0) {
    http_response_code(401);
    echo json_encode(["success" => false, "error" => "unauthorized"]);
    exit;
}

if ($currentPassword === "" || $newPassword === "" || $confirmPassword === "") {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "missing_fields"]);
    exit;
}

if (strlen($newPassword) < 6) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "password_too_short"]);
    exit;
}

if ($newPassword !== $confirmPassword) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "password_mismatch"]);
    exit;
}

$stmt = $pdo->prepare("SELECT password FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$userId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    http_response_code(404);
    echo json_encode(["success" => false, "error" => "user_not_found"]);
    exit;
}

$currentHash = hash("sha256", $currentPassword);
if (!hash_equals((string)$row["password"], $currentHash)) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "current_password_invalid"]);
    exit;
}

$update = $pdo->prepare("UPDATE users SET password = SHA2(?, 256), updated_at = NOW() WHERE id = ?");
$update->execute([$newPassword, $userId]);

echo json_encode(["success" => true, "message" => t("password_changed_success")]);
