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

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

$user = $_SESSION["user"] ?? [];
$userId = (int)($user["id"] ?? 0);
$roleId = (int)($user["role_id"] ?? 0);

if ($roleId !== 3 && $roleId !== 1) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "agency_or_admin_only"]);
    exit;
}

$method = $_SERVER["REQUEST_METHOD"] ?? "GET";

if ($method === "GET") {
    $targetAgencyId = $roleId === 1 ? (int)($_GET["agency_id"] ?? 0) : $userId;
    if ($targetAgencyId <= 0) $targetAgencyId = $userId;

    $uStmt = $pdo->prepare("SELECT agency_is_partner, agency_name, agency_address, agency_tax_id FROM users WHERE id = ? LIMIT 1");
    $uStmt->execute([$targetAgencyId]);
    $u = $uStmt->fetch(PDO::FETCH_ASSOC) ?: ["agency_is_partner" => 1];

    $plan = getLatestAgencyPlan($pdo, $targetAgencyId);

    $invStmt = $pdo->prepare("
        SELECT *
        FROM payment_invoices
        WHERE agency_id = ?
        ORDER BY id DESC
        LIMIT 1
    ");
    $invStmt->execute([$targetAgencyId]);
    $invoice = $invStmt->fetch(PDO::FETCH_ASSOC);

    echo json_encode([
        "success" => true,
        "data" => [
            "is_partner" => (int)($u["agency_is_partner"] ?? 1) === 1,
            "agency" => [
                "name" => (string)($u["agency_name"] ?? ""),
                "address" => (string)($u["agency_address"] ?? ""),
                "tax_id" => (string)($u["agency_tax_id"] ?? "")
            ],
            "plan" => $plan ?: null,
            "invoice" => $invoice ?: null,
            "plans" => [
                "AGENCY_ESSENCE" => getAgencyPlanConfig("AGENCY_ESSENCE"),
                "AGENCY_PRIME" => getAgencyPlanConfig("AGENCY_PRIME"),
                "AGENCY_PRESTIGE" => getAgencyPlanConfig("AGENCY_PRESTIGE")
            ]
        ]
    ]);
    exit;
}

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

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

if (!requireCsrfFromPayload($input, "csrf")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "invalid_csrf"]);
    exit;
}

$targetAgencyId = $roleId === 1 ? (int)($input["agency_id"] ?? 0) : $userId;
if ($targetAgencyId <= 0) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_agency"]);
    exit;
}

$planCode = trim((string)($input["plan_code"] ?? ""));
$agencyName = trim((string)($input["agency_name"] ?? ""));
$agencyAddress = trim((string)($input["agency_address"] ?? ""));
$agencyTaxId = trim((string)($input["agency_tax_id"] ?? ""));

$plan = getAgencyPlanConfig($planCode);
if (!$plan) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_plan_code"]);
    exit;
}
if ($agencyName === "" || $agencyAddress === "") {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "agency_name_and_address_required"]);
    exit;
}

$settings = getPaymentSettings($pdo);
$deadlineDays = max(1, (int)($settings["payment_terms_days"] ?? 7));
$deadlineDate = date("Y-m-d", strtotime("+" . $deadlineDays . " day"));

$pdo->beginTransaction();
try {
    $markNonPartner = $pdo->prepare("UPDATE users SET agency_is_partner = 0 WHERE id = ?");
    $markNonPartner->execute([$targetAgencyId]);

    $closeOld = $pdo->prepare("
        UPDATE agency_worker_plans
        SET status = CASE
            WHEN status = 'active' THEN 'used'
            WHEN status = 'pending' THEN 'cancelled'
            ELSE status
        END,
        updated_at = NOW()
        WHERE agency_id = ? AND status IN ('active','pending')
    ");
    $closeOld->execute([$targetAgencyId]);

    $ins = $pdo->prepare("
        INSERT INTO agency_worker_plans (
            agency_id, plan_code, amount, worker_quota, workers_added, status, starts_at, expires_at, created_at, updated_at
        )
        VALUES (?, ?, ?, ?, 0, 'pending', NULL, NULL, NOW(), NOW())
    ");
    $ins->execute([$targetAgencyId, $planCode, $plan["amount"], $plan["quota"]]);
    $agencyPlanId = (int)$pdo->lastInsertId();

    $reference = generateInvoiceReference("AGY");
    $inv = $pdo->prepare("
        INSERT INTO payment_invoices (
            invoice_type, agency_id, agency_plan_id, company_name, company_address, company_tax_id,
            selected_plan, amount_due, reference_number, bank_name, bank_account, bank_swift,
            payment_deadline, status, created_at, updated_at
        )
        VALUES (
            'agency_worker_plan', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW()
        )
    ");
    $inv->execute([
        $targetAgencyId,
        $agencyPlanId,
        $agencyName,
        $agencyAddress,
        $agencyTaxId !== "" ? $agencyTaxId : null,
        $plan["label"],
        $plan["amount"],
        $reference,
        $settings["bank_name"],
        $settings["bank_account"],
        $settings["bank_swift"],
        $deadlineDate
    ]);

    $updAgency = $pdo->prepare("
        UPDATE users
        SET agency_name = ?, agency_address = ?, agency_tax_id = ?
        WHERE id = ?
    ");
    $updAgency->execute([$agencyName, $agencyAddress, $agencyTaxId !== "" ? $agencyTaxId : null, $targetAgencyId]);

    $pdo->commit();

    echo json_encode([
        "success" => true,
        "message" => "agency_plan_created_pending_admin_confirmation",
        "data" => [
            "agency_plan_id" => $agencyPlanId,
            "reference_number" => $reference,
            "payment_deadline" => $deadlineDate
        ]
    ]);
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(["success" => false, "error" => "failed_to_create_agency_plan"]);
}
?>
