<?php



require_once __DIR__ . '/../../config.php';

// GET /admin/distribuidores/list.php
// Query params: search, status, centro, page, limit
// Header: Authorization: Bearer <token>

requireAdmin();

$db = getDB();
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = min(100, max(1, (int)($_GET['limit'] ?? 20)));
$offset = ($page - 1) * $limit;
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$centro = $_GET['centro'] ?? '';

// Build query
$where = [];
$params = [];

if (!empty($search)) {
    $where[] = '(i.nombre LIKE ? OR i.appat LIKE ? OR i.apmat LIKE ? OR i.email LIKE ?)';
    $searchTerm = '%' . $search . '%';
    array_push($params, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
}

if (!empty($status)) {
    $where[] = 'i.estatus_idestatus = ?';
    $params[] = $status;
}

if (!empty($centro)) {
    $where[] = 'i.centros_idcd = ?';
    $params[] = $centro;
}

$whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

// Count total
$countSql = "SELECT COUNT(*) as total FROM inversionista i $whereClause";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = $stmt->fetch()['total'] ?? 0;

// Fetch paginated results
$sql = "
    SELECT i.id_inver, i.nombre, i.appat, i.apmat, i.email, i.tel1, 
           i.centros_idcd, i.estatus_idestatus, i.referencia, i.estampa,
           c.nombre as centro_nombre, e.descripcion as estatus_nombre
    FROM inversionista i
    LEFT JOIN centros c ON i.centros_idcd = c.idcd
    LEFT JOIN estatus e ON i.estatus_idestatus = e.idestatus
    $whereClause
    ORDER BY i.id_inver DESC
    LIMIT ? OFFSET ?
";

$params[] = $limit;
$params[] = $offset;

$stmt = $db->prepare($sql);
$stmt->execute($params);
$distribuidores = $stmt->fetchAll();

jsonOk([
    'distribuidores' => $distribuidores,
    'pagination' => [
        'page' => $page,
        'limit' => $limit,
        'total' => (int)$total,
        'pages' => (int)ceil($total / $limit)
    ]
]);
