<?php
session_start();
if (!isset($_SESSION["user_id"])) { die('Acceso denegado'); }

require_once 'core/autoload.php';
require_once 'core/app/model/ContractData.php';

$contractId = $_GET['contract_id'] ?? null;
$c = ContractData::getById($contractId);
if (!$c) { 
    echo "Contrato no encontrado";
    exit;
}

$config = ContractConfigData::get();
if (!$config) { 
    $config = new stdClass();
    $config->org_name = 'Consultora Tykun';
    $config->org_address = '';
    $config->org_phone = '';
    $config->org_email = '';
}

require_once 'fpdf186/fpdf.php';

date_default_timezone_set('America/La_Paz');

class ReceiptPDF extends FPDF
{
    function Header()
    {
        $this->SetFont('Arial', 'B', 13);
        $this->SetTextColor(30, 30, 30);
        $this->SetXY(14, 10);
        $this->Cell(0, 7, iconv('UTF-8', 'windows-1252', 'COMPROBANTE DE PAGO'), 0, 1, 'C');
        $this->SetFont('Arial', 'B', 12);
        $this->SetXY(14, 18);
        $this->Cell(0, 7, iconv('UTF-8', 'windows-1252', 'CONSULTORA TYKUN'), 0, 1, 'C');
        $this->SetDrawColor(0, 102, 204);
        $this->SetLineWidth(0.8);
        $this->Line(14, 28, 196, 28);
        $this->Ln(6);
    }

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

    function infoRow($label, $value) {
        $this->SetFont('Arial', 'B', 10);
        $this->SetFillColor(240, 245, 255);
        $this->Cell(50, 7, iconv('UTF-8', 'windows-1252', $label), 0, 0, 'L', true);
        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 7, iconv('UTF-8', 'windows-1252', $value), 0, 1, 'L');
    }
}

function numToLetras($num) {
    $entero = (int)$num;
    $cents  = round(($num - $entero) * 100);
    
    $units = ['', 'Un', 'Dos', 'Tres', 'Cuatro', 'Cinco', 'Seis', 'Siete', 'Ocho', 'Nueve', 'Diez', 
              'Once', 'Doce', 'Trece', 'Catorce', 'Quince', 'Dieciséis', 'Diecisiete', 'Dieciocho', 'Diecinueve'];
    $tens = ['', '', 'Veinte', 'Treinta', 'Cuarenta', 'Cincuenta', 'Sesenta', 'Setenta', 'Ochenta', 'Noventa'];
    $hundreds = ['', 'Cien', 'Doscientos', 'Trescientos', 'Cuatrocientos', 'Quinientos', 'Seiscientos', 'Setecientos', 'Ochocientos', 'Novecientos'];
    
    if ($entero == 0) {
        return 'Cero ' . sprintf('%02d', $cents) . '/100 Bolivianos';
    }
    
    $result = '';
    
    // Thousands
    if ($entero >= 1000) {
        $thousands = (int)($entero / 1000);
        if ($thousands == 1) {
            $result .= 'Mil ';
        } else {
            $result .= numToLetrasSimple($thousands, $units, $tens, $hundreds) . ' Mil ';
        }
        $entero = $entero % 1000;
    }
    
    $result .= numToLetrasSimple($entero, $units, $tens, $hundreds);
    
    return $result . ' ' . sprintf('%02d', $cents) . '/100 Bolivianos';
}

function numToLetrasSimple($num, $units, $tens, $hundreds) {
    if ($num == 0) return '';
    
    if ($num < 20) {
        return $units[$num];
    }
    
    if ($num < 100) {
        $dec = (int)($num / 10) * 10;
        $uni = $num % 10;
        if ($uni == 0) {
            return $tens[$dec / 10];
        }
        return $tens[$dec / 10] . ' y ' . strtolower($units[$uni]);
    }
    
    if ($num < 1000) {
        $cen = (int)($num / 100);
        $rest = $num % 100;
        if ($rest == 0) {
            return $hundreds[$cen];
        }
        return $hundreds[$cen] . ' ' . numToLetrasSimple($rest, $units, $tens, $hundreds);
    }
    
    return $num;
}

$pdf = new ReceiptPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetMargins(14, 32, 14);
$pdf->SetAutoPageBreak(true, 20);

$fechaActual = date('d \d\e F \d\e Y');
$meses = ['January'=>'enero','February'=>'febrero','March'=>'marzo','April'=>'abril','May'=>'mayo','June'=>'junio',
    'July'=>'julio','August'=>'agosto','September'=>'septiembre','October'=>'octubre','November'=>'noviembre','December'=>'diciembre'];
foreach ($meses as $en => $es) {
    $fechaActual = str_replace($en, $es, $fechaActual);
}

$montoTotal = $c->amount;
$anticipo = $montoTotal / 2;
$montoLetras = numToLetras($anticipo);

$pdf->SetFont('Arial', 'B', 11);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 8, iconv('UTF-8', 'windows-1252', 'DETALLES DEL PAGO'), 0, 1, 'L');
$pdf->SetDrawColor(0, 102, 204);
$pdf->SetLineWidth(0.4);
$pdf->Line(14, $pdf->GetY(), 196, $pdf->GetY());
$pdf->Ln(5);

$pdf->infoRow('Nro. Comprobante:', 'CP-' . str_replace('/', '-', $c->cite));
$pdf->infoRow('Fecha:', 'La Paz, ' . $fechaActual);
$pdf->infoRow('Contrato de Referencia:', $c->cite);
$pdf->Ln(5);

$pdf->infoRow('Proveedor (EL PRESTADOR):', $c->part_a_name);
if (!empty($c->part_a_address)) {
    $pdf->infoRow('Direccion:', $c->part_a_address);
}
$pdf->Ln(5);

$pdf->infoRow('Cliente (EL CLIENTE):', $c->part_b_name);
if (!empty($c->part_b_cargo)) {
    $pdf->infoRow('Atencion:', $c->part_b_cargo);
}
if (!empty($c->part_b_address)) {
    $pdf->infoRow('Direccion:', $c->part_b_address);
}
$pdf->Ln(8);

$pdf->SetFont('Arial', 'B', 11);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 8, iconv('UTF-8', 'windows-1252', 'CONCEPTO DE PAGO'), 0, 1, 'L');
$pdf->SetDrawColor(0, 102, 204);
$pdf->Line(14, $pdf->GetY(), 196, $pdf->GetY());
$pdf->Ln(5);

$pdf->infoRow('Monto Total del Contrato:', 'Bs. ' . number_format($montoTotal, 2, ',', '.'));
$pdf->infoRow('Pago por Adelantado (50%):', 'Bs. ' . number_format($anticipo, 2, ',', '.'));
$pdf->infoRow('Forma de Pago:', '50% ANTICIPO 50% CONTRAENTREGA');
$pdf->infoRow('Monto del Anticipo:', 'Bs. ' . number_format($anticipo, 2, ',', '.'));

$pdf->Ln(5);
$pdf->SetFont('Arial', '', 10);
$pdf->SetTextColor(30, 30, 30);
$pdf->MultiCell(0, 5.5, iconv('UTF-8', 'windows-1252', 
    'Por el presente comprobante se deja constancia que se ha recibido la suma de ' . 
    $montoLetras . ' (' . number_format($anticipo, 2, ',', '.') . ') ' . 
    'en concepto de anticipo del contrato de prestación de servicios referido anteriormente.'
), 0, 'J');
$pdf->Ln(10);

$pdf->SetFont('Arial', 'B', 11);
$pdf->SetTextColor(0, 51, 153);
$pdf->Cell(0, 8, iconv('UTF-8', 'windows-1252', 'FIRMA DE CONFORMIDAD'), 0, 1, 'L');
$pdf->SetDrawColor(0, 102, 204);
$pdf->Line(14, $pdf->GetY(), 196, $pdf->GetY());
$pdf->Ln(15);

$pdf->SetFont('Arial', '', 11);
$pdf->SetTextColor(30, 30, 30);

$xLeft = 30;
$xRight = 110;

$pdf->Cell(80, 5, iconv('UTF-8', 'windows-1252', $c->signature_a_name), 0, 0, 'L');
$pdf->Cell(80, 5, iconv('UTF-8', 'windows-1252', $c->signature_b_name ?: $c->part_b_name), 0, 1, 'L');

$pdf->Ln(15);
$pdf->SetFont('Arial', 'I', 9);
$pdf->SetTextColor(100, 100, 100);
$pdf->Cell(0, 5, iconv('UTF-8', 'windows-1252', 'Este comprobante es parte integral del contrato ' . $c->cite), 0, 1, 'C');

$filename = 'Comprobante_Pago_' . str_replace('/', '_', $c->cite) . '.pdf';
$pdf->Output('I', $filename);
exit;
