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

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

function ensureResetRequestsTable(PDO $pdo): void {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS password_reset_requests (
            id INT AUTO_INCREMENT PRIMARY KEY,
            email VARCHAR(100) NOT NULL,
            status ENUM('pending','processed') DEFAULT 'pending',
            requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            processed_by INT NULL,
            processed_at TIMESTAMP NULL,
            generated_password VARCHAR(255) NULL
        )
    ");
}

ensureResetRequestsTable($pdo);

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $payload = json_decode(file_get_contents("php://input"), true) ?: [];
    $action = trim((string)($payload["action"] ?? ""));

    if ($action === "request") {
        $email = trim((string)($payload["email"] ?? ""));
        if ($email === "" || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            http_response_code(422);
            echo json_encode(["success" => false, "error" => "invalid_email"]);
            exit;
        }

        $u = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        $u->execute([$email]);
        if (!$u->fetch(PDO::FETCH_ASSOC)) {
            http_response_code(422);
            echo json_encode(["success" => false, "error" => "email_not_found"]);
            exit;
        }

        $existing = $pdo->prepare("
            SELECT id FROM password_reset_requests
            WHERE email = ? AND status = 'pending'
            ORDER BY id DESC
            LIMIT 1
        ");
        $existing->execute([$email]);
        $existingRow = $existing->fetch(PDO::FETCH_ASSOC);

        if (!$existingRow) {
            $ins = $pdo->prepare("INSERT INTO password_reset_requests (email, status) VALUES (?, 'pending')");
            $ins->execute([$email]);
        }

        echo json_encode(["success" => true, "message" => t("reset_request_sent_admin")]);
        exit;
    }

    requireApiAuth();
    if (!hasPermission("manage_users")) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "forbidden"]);
        exit;
    }

    if (!requireCsrfFromPayload($payload, "csrf")) {
        http_response_code(419);
        echo json_encode(["success" => false, "error" => "csrf_failed"]);
        exit;
    }

    if ($action !== "generate") {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "invalid_action"]);
        exit;
    }

    $requestId = (int)($payload["request_id"] ?? 0);
    if ($requestId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "invalid_request_id"]);
        exit;
    }

    $reqStmt = $pdo->prepare("SELECT * FROM password_reset_requests WHERE id = ? AND status = 'pending' LIMIT 1");
    $reqStmt->execute([$requestId]);
    $req = $reqStmt->fetch(PDO::FETCH_ASSOC);
    if (!$req) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "request_not_found"]);
        exit;
    }

    $email = (string)$req["email"];
    $tempPassword = substr(bin2hex(random_bytes(6)), 0, 12);

    $pdo->beginTransaction();
    try {
        $up = $pdo->prepare("UPDATE users SET password = SHA2(?, 256), updated_at = NOW() WHERE email = ?");
        $up->execute([$tempPassword, $email]);

        $done = $pdo->prepare("
            UPDATE password_reset_requests
            SET status = 'processed',
                processed_by = ?,
                processed_at = NOW(),
                generated_password = ?
            WHERE id = ?
        ");
        $done->execute([(int)($_SESSION["user"]["id"] ?? 0), $tempPassword, $requestId]);

        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(["success" => false, "error" => "reset_update_failed"]);
        exit;
    }

    $subject = t("password_reset_request");
    $message = t("admin_generated_password_email") . "\n\n" . t("new_password") . ": " . $tempPassword;
    $headers = "From: noreply@konzona.com";

    @mail($email, $subject, $message, $headers);

    echo json_encode(["success" => true, "message" => t("temporary_password_sent")]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "GET") {
    requireApiAuth();
    if (!hasPermission("manage_users")) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "forbidden"]);
        exit;
    }

    $rows = $pdo->query("
        SELECT id, email, status, requested_at, processed_at
        FROM password_reset_requests
        ORDER BY requested_at DESC
        LIMIT 100
    ")->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(["success" => true, "data" => $rows]);
    exit;
}

http_response_code(405);
echo json_encode(["success" => false, "error" => "method_not_allowed"]);
