<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

require_once dirname(__DIR__) . '/services/billing.php';
require_once dirname(__DIR__) . '/services/plan_guard.php';
require_once dirname(__DIR__) . '/middleware/roles.php';

$db  = DB::connect();
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Solo seller y super_admin acceden a rutas /seller/*
RoleMiddleware::requireRole(['seller', 'super_admin']);
$ctx = RoleMiddleware::context();

// ── GET /seller — redirect a /seller/recursos ─────────────────────────────────
if ($uri === '/seller') {
    header('Location: /seller/recursos');
    exit;
}

// ── GET /seller/recursos — hub de recursos para el vendedor ───────────────────
if ($uri === '/seller/recursos') {
    [$where, $params] = RoleMiddleware::tenantScope($db);

    $stmt = $db->prepare(
        "SELECT t.id, t.plan, t.billing_status, t.mrr FROM tenants t WHERE $where AND t.deleted_at IS NULL"
    );
    $stmt->execute($params);
    $tenants  = $stmt->fetchAll();
    $totalMrr = array_sum(array_column($tenants, 'mrr'));
    $activos  = count(array_filter($tenants, fn($t) => $t['billing_status'] === 'active'));

    $pendComm = 0;
    $sellerId = $ctx['seller_profile_id'];
    if ($sellerId) {
        $cs = $db->prepare("SELECT COALESCE(SUM(monto),0) FROM commissions WHERE seller_id = :sid AND pagada = 0");
        $cs->execute([':sid' => $sellerId]);
        $pendComm = (float)$cs->fetchColumn();
    }

    require dirname(__DIR__) . '/views/seller/recursos.php';
    exit;
}

// ── GET /seller/tenants — pipeline del vendedor ───────────────────────────────
if ($uri === '/seller/tenants') {
    [$where, $params] = RoleMiddleware::tenantScope($db);

    $stmt = $db->prepare(
        "SELECT t.id, t.name, t.plan, t.billing_status, t.billing_method,
                t.mrr, t.setup_paid, t.current_period_end,
                t.created_at, u.email AS owner_email, u.name AS owner_name
         FROM tenants t
         LEFT JOIN users u ON u.tenant_id = t.id AND u.role = 'owner'
         WHERE $where AND t.deleted_at IS NULL
         ORDER BY t.created_at DESC"
    );
    $stmt->execute($params);
    $tenants = $stmt->fetchAll();

    // KPIs del seller
    $totalMrr  = array_sum(array_column($tenants, 'mrr'));
    $activos   = count(array_filter($tenants, fn($t) => $t['billing_status'] === 'active'));
    $sellerId  = $ctx['seller_profile_id'];

    $pendComm = 0;
    if ($sellerId) {
        $cs = $db->prepare("SELECT COALESCE(SUM(monto),0) FROM commissions WHERE seller_id = :sid AND pagada = 0");
        $cs->execute([':sid' => $sellerId]);
        $pendComm = (float)$cs->fetchColumn();
    }

    require dirname(__DIR__) . '/views/seller/tenants.php';
    exit;
}

// ── GET /seller/commissions — comisiones del vendedor ────────────────────────
if ($uri === '/seller/commissions') {
    $sellerId = $ctx['seller_profile_id'];

    if ($ctx['role'] === 'super_admin' && isset($_GET['seller_id'])) {
        $sellerId = (int)$_GET['seller_id'];
    }

    $stmt = $db->prepare(
        "SELECT c.*, t.name AS tenant_name
         FROM commissions c
         LEFT JOIN tenants t ON t.id = c.tenant_id
         WHERE c.seller_id = :sid
         ORDER BY c.created_at DESC"
    );
    $stmt->execute([':sid' => $sellerId]);
    $commissions = $stmt->fetchAll();

    $totalPend  = array_sum(array_column(array_filter($commissions, fn($c) => !$c['pagada']), 'monto'));
    $totalPagado = array_sum(array_column(array_filter($commissions, fn($c) => $c['pagada']),  'monto'));

    require dirname(__DIR__) . '/views/seller/commissions.php';
    exit;
}

// ── POST /seller/activate — activar un tenant en cash (desde panel seller) ────
if ($uri === '/seller/activate' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    $tenantId = (int)($_POST['tenant_id'] ?? 0);
    $plan     = $_POST['plan']   ?? 'basic';
    $meses    = (int)($_POST['meses'] ?? 1);

    if (!$tenantId) {
        http_response_code(400);
        echo json_encode(['error' => 'tenant_id requerido']);
        exit;
    }

    RoleMiddleware::requireTenantAccess($db, $tenantId, true);
    $sellerId = $ctx['role'] === 'seller' ? (int)$ctx['seller_profile_id'] : null;

    try {
        BillingService::activarCash($db, $tenantId, $plan, $meses, $sellerId);
        echo json_encode(['ok' => true]);
    } catch (RuntimeException $e) {
        http_response_code(400);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

http_response_code(404);
echo '404 Not Found';
