<?php
ob_start();
include('ajax/is_logged.php');
require('fpdf/fpdf.php');
require_once ("config/db.php");
require_once ("config/conexion.php");

error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

// 1. OBTENER TASA
$con_tasa = mysqli_query($con, "SELECT * FROM tasa WHERE id_tasa='1'");
$dato_tasa = mysqli_fetch_array($con_tasa);
$tasa_actual = $dato_tasa['tasa'];
$tax = floatval(TAX);

// 2. PARÁMETROS DE FECHA
$desde = $_GET['desde'];
$hasta = $_GET['hasta'];

// 3. CONSULTA
$sWhere = " WHERE 1=1 ";
if (!empty($desde) && !empty($hasta)) {
    $sWhere .= " AND fecha BETWEEN '$desde' AND '$hasta' ";
}
$sWhere .= " ORDER BY id_compra DESC";
$query = mysqli_query($con, "SELECT * FROM compras $sWhere");
$check_det = mysqli_query($con, "SHOW COLUMNS FROM detalle_compra LIKE 'exento'");
if (!$check_det || mysqli_num_rows($check_det) == 0) {
    mysqli_query($con, "ALTER TABLE detalle_compra ADD COLUMN exento TINYINT(1) NOT NULL DEFAULT 0");
}

class PDF extends FPDF {
    function Header() {
        $this->Image('img/logotienda.jpeg', 40, 5, 200, 15);
        $this->Ln(15);
        $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 8, 'REPORTE DE COMPRAS DETALLADO', 0, 1, 'C');
        $this->Ln(5);

        // Estilo de la cabecera
        $this->SetFillColor(217, 237, 247); 
        $this->SetFont('Arial', 'B', 7);
        
        // --- FILA 1: AGRUPACIÓN SUPERIOR ---
        $this->Cell(150, 6, '', 0, 0); // Espacio hasta llegar a Exento
        $this->Cell(35, 6, 'Compras No Gravadas', 1, 0, 'C', true); // Sobre Exento
        $this->Cell(35, 6, 'Compras Gravadas', 1, 0, 'C', true);    // Sobre Base Imponible
        $this->Cell(40, 6, '', 0, 1); // Espacio vacío sobre % e IVA

        // --- FILA 2: TÍTULOS DE COLUMNAS ---
        $this->Cell(10, 7, 'Item', 1, 0, 'C', true);
        $this->Cell(18, 7, 'Fecha', 1, 0, 'C', true);
        $this->Cell(22, 7, 'Rif', 1, 0, 'C', true);
        $this->Cell(45, 7, 'Proveedor', 1, 0, 'C', true);
        $this->Cell(15, 7, 'Factura', 1, 0, 'C', true);
        $this->Cell(40, 7, 'Monto Factura IVA', 1, 0, 'C', true);
        $this->Cell(35, 7, 'Exentas o Exoneradas', 1, 0, 'C', true);
        $this->Cell(35, 7, 'Base Imponible', 1, 0, 'C', true);
        $this->Cell(10, 7, '% IVA', 1, 0, 'C', true);
        $this->Cell(30, 7, 'Credito Fiscal', 1, 1, 'C', true);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, utf8_decode('Página ').$this->PageNo().'/{nb}', 0, 0, 'C');
    }
}

$tax = floatval(TAX);
$pdf = new PDF('L', 'mm', 'letter');
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial', '', 7);

$j = 0;
$total_total = 0; $total_excento = 0; $total_base = 0; $total_iva = 0;

while($row = mysqli_fetch_array($query)) {
    $j++;

    $det = mysqli_query($con, "SELECT 
                SUM(cantidad * precio_compra) AS monto_total,
                SUM(IF(exento=1, cantidad * precio_compra, 0)) AS total_exento,
                SUM(IF(exento=0, (cantidad * precio_compra) / (1 + (" . $tax . " / 100)), 0)) AS total_base,
                SUM(IF(exento=0, (cantidad * precio_compra) - (cantidad * precio_compra) / (1 + (" . $tax . " / 100)), 0)) AS total_iva
            FROM detalle_compra WHERE numero_compra='".$row['numero_fact']."' AND id_proveedor='".$row['proveedor']."'");
    $det_row = mysqli_fetch_array($det);

    $total_venta = floatval($det_row['monto_total']);
    $excento = floatval($det_row['total_exento']);
    $base = floatval($det_row['total_base']);
    $iva = floatval($det_row['total_iva']);

    if ($total_venta == 0) {
        $total_venta = floatval($row['total']);
        $base = $total_venta;
        $iva = 0;
        $excento = 0;
    }

    $total_total += $total_venta;
    $total_excento += $excento;
    $total_base += $base;
    $total_iva += $iva;

    // Proveedor
    $id_p = $row['proveedor'];
    $c_p = mysqli_query($con, "SELECT * FROM proveedores WHERE id_pro='$id_p'");
    $d_p = mysqli_fetch_array($c_p);

    $pdf->Cell(10, 7, $j, 'B', 0, 'C');
    $pdf->Cell(18, 7, $row['fecha'], 'B', 0, 'C');
    $pdf->Cell(22, 7, $d_p['rif_proveedor'], 'B', 0, 'L');
    $pdf->Cell(45, 7, utf8_decode(substr($d_p['nombre_proveedor'],0,25)), 'B', 0, 'L');
    $pdf->Cell(15, 7, $row['numero_fact'], 'B', 0, 'C');
    
    $pdf->SetFont('Arial', '', 6);
    $pdf->Cell(40, 7, '$ '.number_format($total_venta,2). ' / Bs '.number_format($total_venta*$tasa_actual,2,',','.'), 'B', 0, 'R');
    $pdf->Cell(35, 7, '$ '.number_format($excento,2). ' / Bs '.number_format($excento*$tasa_actual,2,',','.'), 'B', 0, 'R');
    $pdf->Cell(35, 7, '$ '.number_format($base,2). ' / Bs '.number_format($base*$tasa_actual,2,',','.'), 'B', 0, 'R');
    $pdf->SetFont('Arial', '', 7);
    $pdf->Cell(10, 7, TAX.'%', 'B', 0, 'C');
    $pdf->Cell(30, 7, '$ '.number_format($iva,2). ' / Bs '.number_format($iva*$tasa_actual,2,',','.'), 'B', 1, 'R');
}

// FILA DE TOTALES
$pdf->SetFont('Arial', 'B', 7);
$pdf->SetFillColor(217, 237, 247);
$pdf->Cell(110, 8, 'TOTALES GENERALES', 1, 0, 'R', true);
$pdf->Cell(40, 8, '$ '.number_format($total_total,2,',','.'), 1, 0, 'R', true);
$pdf->Cell(35, 8, '$ '.number_format($total_excento,2,',','.'), 1, 0, 'R', true);
$pdf->Cell(35, 8, '$ '.number_format($total_base,2,',','.'), 1, 0, 'R', true);
$pdf->Cell(10, 8, '', 1, 0, 'C', true);
$pdf->Cell(30, 8, '$ '.number_format($total_iva,2,',','.'), 1, 1, 'R', true);

if (ob_get_length()) ob_end_clean();
$pdf->Output('reporte_compras_ninoburguer.pdf', 'D');
?>