<?php
declare(strict_types=1);

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

$columns = ['vd.factura', 'vd.fecha', 'c.nombre', 'pr.titulo', 'vd.cantidad', 'vd.precio',
            'vd.valor_neto', 'vd.valor_iva', 'v.nombre'];
$p = dtRequestParams($columns);
$conn = db();

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

if ($p['search'] !== '') {
    $where[] = '(vd.factura LIKE ? OR c.nombre LIKE ? OR pr.titulo LIKE ?)';
    $like = '%' . $p['search'] . '%';
    array_push($params, $like, $like, $like);
    $types .= 'sss';
}
if (!empty($_GET['desde'])) {
    $where[] = 'vd.fecha >= ?';
    $params[] = $_GET['desde'];
    $types .= 's';
}
if (!empty($_GET['hasta'])) {
    $where[] = 'vd.fecha <= ?';
    $params[] = $_GET['hasta'];
    $types .= 's';
}
if (!empty($_GET['cod_vendedor'])) {
    $where[] = 'vd.cod_vendedor = ?';
    $params[] = $_GET['cod_vendedor'];
    $types .= 's';
}
if (!empty($_GET['codigo_cliente'])) {
    $where[] = 'vd.codigo_cliente = ?';
    $params[] = $_GET['codigo_cliente'];
    $types .= 's';
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

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

$joinSql = "FROM ventas_detalle vd
            LEFT JOIN clientes c ON c.codigo_cliente = vd.codigo_cliente
            LEFT JOIN productos pr ON pr.codigo = vd.codigo_producto
            LEFT JOIN vendedores v ON v.cod_vendedor = vd.cod_vendedor";

$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 vd.factura, vd.fecha, c.nombre AS cliente, pr.titulo AS producto, vd.cantidad,
               vd.precio, vd.valor_neto, vd.valor_iva, v.nombre AS vendedor
        $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[] = [
        '<a href="factura.php?factura=' . urlencode($r['factura']) . '">' . h($r['factura']) . '</a>',
        h($r['fecha']),
        h($r['cliente']),
        h($r['producto']),
        number_format((float) $r['cantidad'], 2),
        money((float) $r['precio']),
        money((float) $r['valor_neto']),
        money((float) $r['valor_iva']),
        h($r['vendedor']),
    ];
}
$stmt->close();

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