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

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

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

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

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

if ($method === "GET") {
    $invoiceId = (int)($_GET["invoice_id"] ?? 0);

    if ($invoiceId > 0) {
        $stmt = $pdo->prepare("SELECT * FROM payment_invoices WHERE id = ? LIMIT 1");
        $stmt->execute([$invoiceId]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode(["success" => true, "data" => $invoice ?: null]);
        exit;
    }

    $settings = $pdo->query("SELECT * FROM payment_settings ORDER BY id DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);

    $list = $pdo->query("
        SELECT pi.*, c.email AS company_email, a.email AS agency_email
        FROM payment_invoices pi
        LEFT JOIN users c ON c.id = pi.company_id
        LEFT JOIN users a ON a.id = pi.agency_id
        ORDER BY pi.id DESC
    ");
    echo json_encode([
        "success" => true,
        "data" => [
            "settings" => $settings ?: null,
            "invoices" => $list->fetchAll(PDO::FETCH_ASSOC)
        ]
    ]);
    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;
}

$action = trim((string)($input["action"] ?? ""));

if ($action === "update_settings") {
    $bankName = trim((string)($input["bank_name"] ?? ""));
    $bankAccount = trim((string)($input["bank_account"] ?? ""));
    $bankSwift = trim((string)($input["bank_swift"] ?? ""));
    $terms = max(1, (int)($input["payment_terms_days"] ?? 7));

    if ($bankName === "" || $bankAccount === "") {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "bank_name_and_account_required"]);
        exit;
    }

    $stmt = $pdo->prepare("
        INSERT INTO payment_settings (bank_name, bank_account, bank_swift, payment_terms_days, created_at, updated_at)
        VALUES (?, ?, ?, ?, NOW(), NOW())
    ");
    $stmt->execute([$bankName, $bankAccount, $bankSwift, $terms]);

    echo json_encode(["success" => true]);
    exit;
}

if ($action === "confirm_invoice" || $action === "reject_invoice") {
    $invoiceId = (int)($input["invoice_id"] ?? 0);
    if ($invoiceId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "invalid_invoice_id"]);
        exit;
    }

    $invStmt = $pdo->prepare("SELECT * FROM payment_invoices WHERE id = ? LIMIT 1");
    $invStmt->execute([$invoiceId]);
    $invoice = $invStmt->fetch(PDO::FETCH_ASSOC);
    if (!$invoice) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "invoice_not_found"]);
        exit;
    }

    $pdo->beginTransaction();
    try {
        $newStatus = $action === "confirm_invoice" ? "approved" : "rejected";
        $invUp = $pdo->prepare("
            UPDATE payment_invoices
            SET status = ?, approved_by = ?, approved_at = NOW(), updated_at = NOW()
            WHERE id = ?
        ");
        $invUp->execute([$newStatus, $userId, $invoiceId]);

        if ($action === "confirm_invoice") {
            if ((string)$invoice["invoice_type"] === "company_subscription") {
                $subId = (int)($invoice["subscription_id"] ?? 0);
                if ($subId > 0) {
                    $subUp = $pdo->prepare("
                        UPDATE company_subscriptions
                        SET status = 'active',
                            starts_at = NOW(),
                            expires_at = DATE_ADD(NOW(), INTERVAL 1 MONTH),
                            approved_by = ?,
                            approved_at = NOW(),
                            updated_at = NOW()
                        WHERE id = ?
                    ");
                    $subUp->execute([$userId, $subId]);
                }
            } elseif ((string)$invoice["invoice_type"] === "agency_worker_plan") {
                $planId = (int)($invoice["agency_plan_id"] ?? 0);
                if ($planId > 0) {
                    $planStmt = $pdo->prepare("SELECT plan_code FROM agency_worker_plans WHERE id = ? LIMIT 1");
                    $planStmt->execute([$planId]);
                    $planRow = $planStmt->fetch(PDO::FETCH_ASSOC) ?: [];
                    $planCode = strtoupper((string)($planRow["plan_code"] ?? ""));

                    $daysByPlan = [
                        "AGENCY_ESSENCE" => 7,
                        "AGENCY_PRIME" => 15,
                        "AGENCY_PRESTIGE" => 30
                    ];
                    $days = (int)($daysByPlan[$planCode] ?? 30);

                    $planUp = $pdo->prepare("
                        UPDATE agency_worker_plans
                        SET status = 'active',
                            starts_at = NOW(),
                            expires_at = DATE_ADD(NOW(), INTERVAL {$days} DAY),
                            approved_by = ?,
                            approved_at = NOW(),
                            updated_at = NOW()
                        WHERE id = ?
                    ");
                    $planUp->execute([$userId, $planId]);
                }
            }
        }

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

http_response_code(422);
echo json_encode(["success" => false, "error" => "invalid_action"]);
