<?php
require_once __DIR__ . "/../config/database.php";

function getPaymentSettings(PDO $pdo): array {
    $stmt = $pdo->query("SELECT * FROM payment_settings ORDER BY id DESC LIMIT 1");
    $row = $stmt ? $stmt->fetch(PDO::FETCH_ASSOC) : null;
    return $row ?: [
        "bank_name" => "Konzona Bank",
        "bank_account" => "RS35-840-0000000001234-56",
        "bank_swift" => "KONZONARBX",
        "payment_terms_days" => 7
    ];
}

function generateInvoiceReference(string $prefix = "INV"): string {
    return strtoupper($prefix) . "-" . date("YmdHis") . "-" . strtoupper(bin2hex(random_bytes(3)));
}

function getCompanyPlanConfig(string $planCode): ?array {
    $plans = [
        // Updated company subscription options
        "COMPANY_BASIC" => ["label" => "Option 1: €100 (2 requests / 7 days)", "amount" => 100.00, "limit" => 2, "days" => 7],
        "COMPANY_PRO" => ["label" => "Option 2: €220 (5 requests / 15 days)", "amount" => 220.00, "limit" => 5, "days" => 15],
        "COMPANY_ENTERPRISE" => ["label" => "Option 3: €450 (15 requests / 30 days)", "amount" => 450.00, "limit" => 15, "days" => 30],

        // Added consultations (new)
        "COMPANY_REMOTE" => [
            "label" => "Remote (€120/h) - video call, up to 3h",
            "amount" => 120.00,
            "limit" => 1
        ],
        "COMPANY_OB_4" => [
            "label" => "Outside Belgrade Onsite 4 (€600) - up to 4h incl. travel/logistics",
            "amount" => 600.00,
            "limit" => 1
        ],
        "COMPANY_OB_8" => [
            "label" => "Outside Belgrade Onsite 8 (€900) - up to 8h incl. travel/logistics",
            "amount" => 900.00,
            "limit" => 1
        ],
    ];
    return $plans[$planCode] ?? null;
}

function getAgencyPlanConfig(string $planCode): ?array {
    $plans = [
        "AGENCY_ESSENCE" => [
            "label" => "Essence (€100) - 2 worker requests / 7 days / basic profile / no video / limited support",
            "amount" => 100.00,
            "quota" => 2,
            "days" => 7
        ],
        "AGENCY_PRIME" => [
            "label" => "Prime (€220) - 5 worker requests / 15 days / extended profile / video interview / 24/7 support",
            "amount" => 220.00,
            "quota" => 5,
            "days" => 15
        ],
        "AGENCY_PRESTIGE" => [
            "label" => "Prestige (€450) - 15 worker requests / 30 days / full profile / video interview + skills / 24/7 support",
            "amount" => 450.00,
            "quota" => 15,
            "days" => 30
        ],
    ];
    return $plans[$planCode] ?? null;
}

function getLatestCompanySubscription(PDO $pdo, int $companyId): ?array {
    $stmt = $pdo->prepare("
        SELECT *
        FROM company_subscriptions
        WHERE company_id = ?
        ORDER BY id DESC
        LIMIT 1
    ");
    $stmt->execute([$companyId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function getLatestAgencyPlan(PDO $pdo, int $agencyId): ?array {
    $stmt = $pdo->prepare("
        SELECT *
        FROM agency_worker_plans
        WHERE agency_id = ?
        ORDER BY id DESC
        LIMIT 1
    ");
    $stmt->execute([$agencyId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

function companyHasActiveSubscription(PDO $pdo, int $companyId): bool {
    $sub = getLatestCompanySubscription($pdo, $companyId);
    if (!$sub) return false;

    $status = (string)($sub["status"] ?? "");
    $expiresAt = (string)($sub["expires_at"] ?? "");

    if ($status !== "active") return false;
    if ($expiresAt === "") return false;

    return (strtotime($expiresAt) !== false && strtotime($expiresAt) >= time());
}

function agencyCanAddWorkers(PDO $pdo, int $agencyId): bool {
    $uStmt = $pdo->prepare("SELECT agency_is_partner FROM users WHERE id = ? LIMIT 1");
    $uStmt->execute([$agencyId]);
    $isPartner = (int)($uStmt->fetchColumn() ?: 0);
    if ($isPartner === 1) return true;

    $plan = getLatestAgencyPlan($pdo, $agencyId);
    if (!$plan) return false;

    $status = (string)($plan["status"] ?? "");
    $quota = (int)($plan["worker_quota"] ?? 0);
    $used = (int)($plan["workers_added"] ?? 0);

    return $status === "active" && $used < $quota;
}

function enforceCompanyAccessOrRedirect(PDO $pdo, array $user): ?string {
    $roleId = (int)($user["role_id"] ?? 0);
    if ($roleId !== 4) return null;

    $current = basename(parse_url($_SERVER["REQUEST_URI"] ?? "", PHP_URL_PATH) ?: "");
    $hasActive = companyHasActiveSubscription($pdo, (int)$user["id"]);

    if (!$hasActive) {
        if ($current !== "subscription.php") {
            return "subscription.php";
        }
        return null;
    }

    if ($current === "subscription.php") {
        return "dashboard.php";
    }

    return null;
}

function enforceAgencyAddWorkerOrError(PDO $pdo, array $user): ?string {
    $roleId = (int)($user["role_id"] ?? 0);
    if ($roleId !== 3) return null;
    if (!agencyCanAddWorkers($pdo, (int)$user["id"])) {
        return "agency_plan_required";
    }
    return null;
}
?>
