<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$columns = ['r.fecha_recaudo', 'r.nombre_cliente', 'v.nombre', 'r.factura', 'r.valor_recaudo', 'r.tipo_pago'];
$p = dtRequestParams($columns);
$conn = db();

$where = [];
$params = [];
$types = '';

if ($p['search'] !== '') {
    $where[] = '(r.factura LIKE ? OR r.nombre_cliente LIKE ?)';
    $like = '%' . $p['search'] . '%';
    array_push($params, $like, $like);
    $types .= 'ss';
}
if (!empty($_GET['desde'])) {
    $where[] = 'r.fecha_recaudo >= ?';
    $params[] = $_GET['desde'];
    $types .= 's';
}
if (!empty($_GET['hasta'])) {
    $where[] = 'r.fecha_recaudo <= ?';
    $params[] = $_GET['hasta'];
    $types .= 's';
}
if (!empty($_GET['cod_vendedor'])) {
    $where[] = 'r.cod_vendedor = ?';
    $params[] = $_GET['cod_vendedor'];
    $types .= 's';
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$joinSql = "FROM recaudos r LEFT JOIN vendedores v ON v.cod_vendedor = r.cod_vendedor";

$total = (int) $conn->query('SELECT COUNT(*) AS n FROM recaudos')->fetch_assoc()['n'];

$stmt = $conn->prepare("SELECT COUNT(*) AS n $joinSql $whereSql");
if ($types !== '') { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$filtered = (int) $stmt->get_result()->fetch_assoc()['n'];
$stmt->close();

$sql = "SELECT r.fecha_recaudo, r.nombre_cliente, v.nombre AS vendedor, r.factura, r.valor_recaudo, r.tipo_pago
        $joinSql $whereSql
        ORDER BY {$p['orderCol']} {$p['orderDir']}
        LIMIT ?, ?";
$allParams = $params; $allTypes = $types . 'ii';
$allParams[] = $p['start']; $allParams[] = $p['length'];

$stmt = $conn->prepare($sql);
$stmt->bind_param($allTypes, ...$allParams);
$stmt->execute();
$result = $stmt->get_result();

$rows = [];
while ($r = $result->fetch_assoc()) {
    $rows[] = [
        h($r['fecha_recaudo']),
        h($r['nombre_cliente']),
        h($r['vendedor']),
        h($r['factura']),
        money((float) $r['valor_recaudo']),
        h($r['tipo_pago'] ?: '-'),
    ];
}
$stmt->close();

dtRespond($p['draw'], $total, $filtered, $rows);
