<?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");

$method = $_SERVER["REQUEST_METHOD"] ?? "GET";
$isPublicSlip = false;
$inputRaw = null;

if ($method === "POST") {
    $inputRaw = json_decode(file_get_contents("php://input"), true);
    if (is_array($inputRaw) && (int)($inputRaw["allow_public_slip"] ?? 0) === 1) {
        $isPublicSlip = true;
    }
}

if (!$isPublicSlip) {
    requireApiAuth();
}

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

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

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

    $sub = getLatestCompanySubscription($pdo, $targetCompanyId);

    if ($sub && (string)$sub["status"] === "active" && !empty($sub["expires_at"]) && strtotime($sub["expires_at"]) < time()) {
        $exp = $pdo->prepare("UPDATE company_subscriptions SET status = 'expired', updated_at = NOW() WHERE id = ?");
        $exp->execute([(int)$sub["id"]]);
        $sub["status"] = "expired";
    }

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

    echo json_encode([
        "success" => true,
        "data" => [
            "subscription" => $sub ?: null,
            "invoice" => $invoice ?: null,
            "plans" => [
                "COMPANY_BASIC" => getCompanyPlanConfig("COMPANY_BASIC"),
                "COMPANY_PRO" => getCompanyPlanConfig("COMPANY_PRO"),
                "COMPANY_ENTERPRISE" => getCompanyPlanConfig("COMPANY_ENTERPRISE"),
                "COMPANY_REMOTE" => getCompanyPlanConfig("COMPANY_REMOTE"),
                "COMPANY_OB_4" => getCompanyPlanConfig("COMPANY_OB_4"),
                "COMPANY_OB_8" => getCompanyPlanConfig("COMPANY_OB_8")
            ]
        ]
    ]);
    exit;
}

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

$input = is_array($inputRaw) ? $inputRaw : 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 (!$isPublicSlip && !requireCsrfFromPayload($input, "csrf")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "invalid_csrf"]);
    exit;
}

$planCode = trim((string)($input["plan_code"] ?? ""));
$companyName = trim((string)($input["company_name"] ?? ""));
$companyAddress = trim((string)($input["company_address"] ?? ""));
$companyTaxId = trim((string)($input["company_tax_id"] ?? ""));
$companyEmail = trim((string)($input["company_email"] ?? ""));

$targetCompanyId = $roleId === 1 ? (int)($input["company_id"] ?? 0) : $userId;
if (!$isPublicSlip && $targetCompanyId <= 0) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_company"]);
    exit;
}

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

$contactPerson = trim((string)($input["contact_person"] ?? ""));
$phoneNumber = trim((string)($input["phone_number"] ?? ""));

if ($companyName === "" || $companyAddress === "") {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "company_name_and_address_required"]);
    exit;
}

if ($isPublicSlip && ($companyTaxId === "" || $contactPerson === "" || $phoneNumber === "")) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "tax_id_contact_and_phone_required"]);
    exit;
}

if ($companyEmail === "" || !filter_var($companyEmail, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "valid_company_email_required"]);
    exit;
}

$settings = getPaymentSettings($pdo);
if (!is_array($settings)) {
    $settings = [];
}

$bankName = trim((string)($settings["bank_name"] ?? ""));
$bankAccount = trim((string)($settings["bank_account"] ?? ""));
$bankSwift = trim((string)($settings["bank_swift"] ?? ""));

if ($bankName === "") $bankName = "N/A";
if ($bankAccount === "") $bankAccount = "N/A";
if ($bankSwift === "") $bankSwift = "N/A";

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

try {
    $subscriptionId = null;
    if (!$isPublicSlip) {
        $expireOld = $pdo->prepare("
            UPDATE company_subscriptions
            SET status = CASE
                WHEN status = 'active' THEN 'expired'
                WHEN status = 'pending' THEN 'cancelled'
                ELSE status
            END,
            updated_at = NOW()
            WHERE company_id = ? AND status IN ('active','pending')
        ");
        $expireOld->execute([$targetCompanyId]);

        $planDays = (int)($plan["days"] ?? 30);
        if ($planDays <= 0) $planDays = 30;
        $startsAt = date("Y-m-d H:i:s");
        $expiresAt = date("Y-m-d H:i:s", strtotime("+" . $planDays . " days"));

        $ins = $pdo->prepare("
            INSERT INTO company_subscriptions (
                company_id, plan_code, monthly_price, monthly_request_limit, requests_used, status, starts_at, expires_at, created_at, updated_at
            )
            VALUES (?, ?, ?, ?, 0, 'pending', ?, ?, NOW(), NOW())
        ");
        $ins->execute([$targetCompanyId, $planCode, $plan["amount"], $plan["limit"], $startsAt, $expiresAt]);
        $subscriptionId = (int)$pdo->lastInsertId();
    }

    $reference = generateInvoiceReference("CMP");
    $invoiceIns = $pdo->prepare("
        INSERT INTO payment_invoices (
            invoice_type, company_id, subscription_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 (
            'company_subscription', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW()
        )
    ");
    $invoiceCompanyId = $isPublicSlip ? null : $targetCompanyId;

    $invoiceIns->execute([
        $invoiceCompanyId,
        $subscriptionId,
        $companyName,
        $companyAddress,
        $companyTaxId !== "" ? $companyTaxId : null,
        $plan["label"],
        $plan["amount"],
        $reference,
        $bankName,
        $bankAccount,
        $bankSwift,
        $deadlineDate
    ]);
    $invoiceId = (int)$pdo->lastInsertId();

    if (!$isPublicSlip) {
        $userUpdate = $pdo->prepare("
            UPDATE users
            SET company_name = ?, company_address = ?, company_tax_id = ?, email = ?
            WHERE id = ?
        ");
        $userUpdate->execute([
            $companyName,
            $companyAddress,
            $companyTaxId !== "" ? $companyTaxId : null,
            $companyEmail,
            $targetCompanyId
        ]);
    }

    // Strongest package (Prestige) support path when no worker is found:
    // create a support message to all admins/moderators with provided criteria.
    if ($isPublicSlip) {
        $adminTargets = $pdo->prepare("
            SELECT id
            FROM users
            WHERE role_id IN (1,5)
            ORDER BY id ASC
        ");
        $adminTargets->execute();
        $targets = $adminTargets->fetchAll(PDO::FETCH_COLUMN);

        if ($targets && count($targets) > 0) {
            $publicText = "[ACCOUNT CREATION REQUEST] Contact person: " . $contactPerson .
                ", Email: " . $companyEmail .
                ", Phone: " . $phoneNumber .
                ", PIB: " . ($companyTaxId !== "" ? $companyTaxId : "n/a") .
                ", Plan: " . $planCode .
                ", Company: " . $companyName;

            $systemSenderId = 0;
            $findSystem = $pdo->prepare("SELECT id FROM users WHERE role_id IN (1,5) ORDER BY id ASC LIMIT 1");
            $findSystem->execute();
            $systemSenderId = (int)$findSystem->fetchColumn();

            if ($systemSenderId > 0) {
                // Keep only message/notification creation for public pricing requests.
                // requests table has environment-specific NOT NULL/FK constraints.
                $insMsg = $pdo->prepare("
                    INSERT INTO messages (sender_id, receiver_id, text, status, created_at)
                    VALUES (?, ?, ?, 'unread', NOW())
                ");
                $insNotif = $pdo->prepare("
                    INSERT INTO notifications (sender_id, receiver_id, type, message, is_read, created_at)
                    VALUES (?, ?, 'message', ?, 0, NOW())
                ");

                foreach ($targets as $targetId) {
                    $targetId = (int)$targetId;
                    if ($targetId <= 0) continue;
                    $insMsg->execute([$systemSenderId, $targetId, $publicText]);
                    $insNotif->execute([$systemSenderId, $targetId, "New account creation request from pricing form"]);
                }
            }
        }
    }

    if (!$isPublicSlip && $planCode === "COMPANY_ENTERPRISE") {
        $specialCriteria = trim((string)($input["special_criteria"] ?? ""));
        if ($specialCriteria !== "") {
            $senderLookup = $pdo->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
            $senderLookup->execute([$targetCompanyId]);
            $senderId = (int)$senderLookup->fetchColumn();

            if ($senderId > 0) {
                $targetsStmt = $pdo->prepare("
                    SELECT id
                    FROM users
                    WHERE role_id IN (1, 5) AND id <> ?
                    ORDER BY id ASC
                ");
                $targetsStmt->execute([$senderId]);
                $targets = $targetsStmt->fetchAll(PDO::FETCH_COLUMN);

                if ($targets && count($targets) > 0) {
                    $specialText = "[SPECIAL WORKER REQUEST] Company #{$senderId} criteria: " . $specialCriteria;

                    $insMsg = $pdo->prepare("
                        INSERT INTO messages (sender_id, receiver_id, text, status, created_at)
                        VALUES (?, ?, ?, 'unread', NOW())
                    ");
                    $insNotif = $pdo->prepare("
                        INSERT INTO notifications (sender_id, receiver_id, type, message, is_read, created_at)
                        VALUES (?, ?, 'message', ?, 0, NOW())
                    ");

                    foreach ($targets as $targetId) {
                        $targetId = (int)$targetId;
                        if ($targetId <= 0) continue;
                        $insMsg->execute([$senderId, $targetId, $specialText]);
                        $insNotif->execute([$senderId, $targetId, "New special worker request from company #{$senderId}"]);
                    }
                }
            }
        }
    }

    if ($companyEmail !== "") {
        $subject = "Konzona payment slip " . $reference;
        $mailText =
            "Poštovani,\n\n" .
            "Vaš nalog za uplatu je kreiran.\n" .
            "Plan: " . $plan["label"] . "\n" .
            "Iznos: €" . $plan["amount"] . "\n" .
            "Poziv na broj: " . $reference . "\n" .
            "Rok plaćanja: " . $deadlineDate . "\n\n" .
            "Banka: " . $bankName . "\n" .
            "Račun: " . $bankAccount . "\n" .
            "SWIFT: " . $bankSwift . "\n\n" .
            "QR sadržaj:\n" .
            "KONZONA|REF:" . $reference . "|AMOUNT:" . $plan["amount"] . "|ACC:" . $bankAccount . "|SWIFT:" . $bankSwift . "|DEADLINE:" . $deadlineDate . "\n\n" .
            "PDF/Slip endpoint: ../api/subscription_slip_pdf.php?invoice_id=" . $invoiceId . "\n";

        $headers = "From: no-reply@konzona.local\r\n";
        $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

        if (function_exists("mail")) {
            @mail($companyEmail, $subject, $mailText, $headers);
        } else {
            error_log("subscriptions.php: mail() is not available on this host.");
        }
    }

    echo json_encode([
        "success" => true,
        "message" => "subscription_created_pending_admin_confirmation",
        "data" => [
            "subscription_id" => $subscriptionId,
            "invoice_id" => $invoiceId,
            "reference_number" => $reference,
            "payment_deadline" => $deadlineDate,
            "slip_pdf_endpoint" => "../api/subscription_slip_pdf.php?invoice_id=" . $invoiceId
        ]
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    error_log("subscriptions.php failed_to_create_subscription: " . $e->getMessage());
    echo json_encode([
        "success" => false,
        "error" => "failed_to_create_subscription",
        "debug_message" => $e->getMessage()
    ]);
}
?>
