<?php
require_once "../db.php";

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);
if (!is_array($data)) {
    $data = [];
}

$email = trim((string) ($data["email"] ?? ""));
$currentPassword = (string) ($data["currentPassword"] ?? "");
$newPassword = (string) ($data["newPassword"] ?? "");
$confirmPassword = (string) ($data["confirmPassword"] ?? "");

if ($email === "" || $currentPassword === "" || $newPassword === "" || $confirmPassword === "") {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "Email, previous password and new password fields are required"]);
    exit;
}

if ($newPassword !== $confirmPassword) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "New password and confirmation do not match"]);
    exit;
}

if (strlen($newPassword) < 8) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "New password must be at least 8 characters"]);
    exit;
}

$select = $conn->prepare("SELECT id, password, role FROM users WHERE email = ? LIMIT 1");
if (!$select) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to prepare user query"]);
    exit;
}

$select->bind_param("s", $email);
$select->execute();
$result = $select->get_result();

if (!$result || $result->num_rows !== 1) {
    $select->close();
    http_response_code(404);
    echo json_encode(["status" => "error", "message" => "User not found"]);
    exit;
}

$user = $result->fetch_assoc();
$select->close();

if ($user["role"] !== "admin") {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Only admin password can be changed from this endpoint"]);
    exit;
}

if (!password_verify($currentPassword, $user["password"])) {
    http_response_code(401);
    echo json_encode(["status" => "error", "message" => "Previous password is incorrect"]);
    exit;
}

if (password_verify($newPassword, $user["password"])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "New password must be different from previous password"]);
    exit;
}

$newHash = password_hash($newPassword, PASSWORD_BCRYPT);
$update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
if (!$update) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to prepare update query"]);
    exit;
}

$userId = (int) $user["id"];
$update->bind_param("si", $newHash, $userId);
$ok = $update->execute();
$update->close();

if (!$ok) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Could not update password"]);
    exit;
}

echo json_encode(["status" => "success", "message" => "Password updated successfully"]);
$conn->close();

