<?php
// @php83-utf8-shim
if (!function_exists("utf8_encode")) { function utf8_encode($s) { return mb_convert_encoding($s, "UTF-8", "ISO-8859-1"); } }
if (!function_exists("utf8_decode")) { function utf8_decode($s) { return mb_convert_encoding($s, "ISO-8859-1", "UTF-8"); } }
session_start();
require("fpdf186/fpdf.php");
require_once("QRcode/qrcode.class.php");
header("Content-Type: text/html; charset=UTF-8");

date_default_timezone_set("America/La_Paz");
include "core/autoload.php";

include "core/app/model/ChanceData.php";
include "core/app/model/PersonData.php";
include "core/app/model/ContactData.php";
include "core/app/model/PaymentData.php";
include "core/app/model/ProductData.php";
include "core/app/model/ProductosData.php";
include "core/app/model/ProductStockData.php";
include "core/app/model/ProposalData.php";
include "core/app/model/ProposalDetailData.php";
include "core/app/model/ProposalQuoteData.php";
include "core/app/model/UserData.php";
include "core/app/model/BrandData.php";
include "core/app/model/DeliveryActData.php";
include "core/app/model/DeliveryActDetailData.php";

class PDF extends FPDF
{
    protected $widths;
    protected $aligns;

    function SetWidths($w)
    {
        $this->widths = $w;
    }

    function SetAligns($a)
    {
        $this->aligns = $a;
    }

    function Row($data)
    {
        $nb = 0;
        for ($i = 0; $i < count($data); $i++)
            $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 5 * $nb;
        $this->CheckPageBreak($h);
        for ($i = 0; $i < count($data); $i++) {
            $w = $this->widths[$i];
            $a = isset($this->aligns[$i]) ? $this->aligns[$i] : "L";
            $x = $this->GetX();
            $y = $this->GetY();
            $this->MultiCell($w, 5, $data[$i], 0, $a);
            $this->SetXY($x + $w, $y);
        }
        $this->Ln($h);
    }

    function CheckPageBreak($h)
    {
        if ($this->GetY() + $h > $this->PageBreakTrigger)
            $this->AddPage($this->CurOrientation);
    }

    function NbLines($w, $txt)
    {
        if (!isset($this->CurrentFont))
            $this->Error("No font has been set");
        $cw = $this->CurrentFont["cw"];
        if ($w == 0)
            $w = $this->w - $this->rMargin - $this->x;
        $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
        $s = str_replace("\r", "", (string)$txt);
        $nb = strlen($s);
        if ($nb > 0 && $s[$nb - 1] == "\n")
            $nb--;
        $sep = -1;
        $i = 0;
        $j = 0;
        $l = 0;
        $nl = 1;
        while ($i < $nb) {
            $c = $s[$i];
            if ($c == "\n") {
                $i++;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
                continue;
            }
            if ($c == " ")
                $sep = $i;
            $l += $cw[$c];
            if ($l > $wmax) {
                if ($sep == -1) {
                    if ($i == $j)
                        $i++;
                } else
                    $i = $sep + 1;
                $sep = -1;
                $j = $i;
                $l = 0;
                $nl++;
            } else
                $i++;
        }
        return $nl;
    }

    function Header()
    {
        $act = DeliveryActData::getById($_GET["id"]);
        $client = PersonData::getById($act->person_id);
        $us = UserData::getById($act->user_id);

        if ($this->PageNo() == 1) {
            // Logo
            $this->SetFillColor(0, 0, 0);
            $this->Image("logo_tykun.png", 140, 10, 60);
            $this->Cell(189, 20, "", 0, 1);

            // Titulo
            $this->SetFont("Arial", "B", 18);
            $this->SetXY(14, 10);
            $this->Cell(50, 10, mb_convert_encoding("ACTA DE ENTREGA", "ISO-8859-1", "UTF-8"), 0, 0, "L");

            // Numero de Acta
            $this->SetTextColor(0, 153, 255);
            $this->SetFont("Arial", "B", 10);
            $this->SetXY(14, 20);
            $this->Cell(5, 4, "AE-" . str_pad($act->id, 5, "0", STR_PAD_LEFT) . "/" . date("Y"), 0, 0);
            $this->SetTextColor(0, 0, 0);

            // Fecha
            $this->SetXY(14, 25);
            $this->SetFont("Arial", "B", 10);
            $this->Cell(40, 10, mb_convert_encoding("Fecha: ", "ISO-8859-1"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $this->SetXY(28, 25);
            $this->Cell(40, 10, $GLOBALS["dia"] . "/" . $GLOBALS["mes"] . "/" . $GLOBALS["anio"], 0, 0, "L");

            // Linea azul
            $this->SetDrawColor(0, 153, 255);
            $this->SetLineWidth(0.6);
            $this->Line(14, 42, 200, 42);

            // Datos de TYKUN (derecha)
            $this->SetFont("Arial", "", 8);
            $this->SetXY(200, 30);
            $this->Cell(1, 1, mb_convert_encoding("Calle Manuel Mariaca Nro 1280", "ISO-8859-1", "UTF-8"), 0, 0, "R");
            $this->SetXY(200, 35);
            $this->Cell(1, 1, mb_convert_encoding("Edificio Espacio Miraflores", "ISO-8859-1", "UTF-8"), 0, 0, "R");
            $this->SetXY(200, 40);
            $this->Cell(1, 1, mb_convert_encoding("La Paz - Bolivia", "ISO-8859-1", "UTF-8"), 0, 0, "R");
            $this->SetXY(200, 45);
            $this->Cell(1, 1, mb_convert_encoding("63167327 - 60695047", "ISO-8859-1", "UTF-8"), 0, 0, "R");
            $this->SetXY(200, 50);
            $this->Cell(1, 1, mb_convert_encoding("info@consultora-tykun.com", "ISO-8859-1", "UTF-8"), 0, 0, "R");

            // Cliente
            $this->SetFont("Arial", "B", 10);
            $this->SetXY(14, 55);
            $this->Cell(40, 10, mb_convert_encoding("Cliente: ", "ISO-8859-1", "UTF-8"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $this->SetXY(35, 55);
            $client_name = trim((string)($client->name_c ?? ""));
            if ($client_name === "") {
                $client_name = trim((string)($client->name ?? "Sin cliente"));
            }
            $this->Cell(80, 10, mb_convert_encoding(html_entity_decode($client_name, ENT_QUOTES | ENT_HTML5, "UTF-8"), "ISO-8859-1", "UTF-8"), 0, 0, "L");

            // Linea ploma
            $this->SetDrawColor(211, 211, 211);
            $this->Line(14, 65, 200, 65);

            // Datos del proyecto
            $this->SetXY(14, 73);
            $lineHeight = 6;
            $labelWidth = 50;
            $valueWidth = 150;

            // Referencia
            $this->SetFont("Arial", "B", 10);
            $this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Referencia:", "ISO-8859-1"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $ref = isset($act->reference) ? html_entity_decode($act->reference, ENT_QUOTES | ENT_HTML5, "UTF-8") : "-";
            $this->Cell($valueWidth, $lineHeight, mb_convert_encoding($ref, "ISO-8859-1"), 0, 1, "L");
            $this->SetXY(14, 79);

            // Lugar de Entrega
            $this->SetFont("Arial", "B", 10);
            $this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Lugar de Entrega:", "ISO-8859-1"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $place = isset($act->place) ? html_entity_decode($act->place, ENT_QUOTES | ENT_HTML5, "UTF-8") : "-";
            $this->Cell($valueWidth, $lineHeight, mb_convert_encoding($place, "ISO-8859-1"), 0, 1, "L");
            $this->SetXY(14, 85);

            // Fecha de Entrega
            $this->SetFont("Arial", "B", 10);
            $this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Fecha de Entrega:", "ISO-8859-1"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $delivery_date = isset($act->delivery_date) ? date("d/m/Y", strtotime($act->delivery_date)) : "-";
            $this->Cell($valueWidth, $lineHeight, mb_convert_encoding($delivery_date, "ISO-8859-1"), 0, 1, "L");
            $this->SetXY(14, 91);

            // Garantia
            $this->SetFont("Arial", "B", 10);
            $this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Garantia:", "ISO-8859-1"), 0, 0, "L");
            $this->SetFont("Arial", "", 10);
            $warranty = isset($act->warranty) ? $act->warranty : 12;
            $this->Cell($valueWidth, $lineHeight, mb_convert_encoding($warranty . " meses", "ISO-8859-1"), 0, 1, "L");

            $this->Ln(15);
        }
    }

    function Footer()
    {
        $this->SetY(-10);
        $this->SetFont("Arial", "B", 8);
        $totalWidth = 60 + 60 + 60;
        $pageWidth = $this->GetPageWidth();
        $startX = ($pageWidth - $totalWidth) / 2;
        $this->SetX($startX);
        $this->SetDrawColor(0, 0, 0);
        $this->SetLineWidth(0.2);
        $this->SetDrawColor(255, 255, 255);
        $this->Cell(60, 5, "TYKUN", 1, 0, "C");
        $this->Cell(60, 5, "Codigo: AE-" . str_pad($act->id, 5, "0", STR_PAD_LEFT), 1, 0, "C");
        $this->Cell(60, 5, "V: 31/12/2026", 1, 1, "C");
        $this->SetDrawColor(211, 211, 211);
        $this->SetLineWidth(0.6);
        $this->Line(14, 267, 200, 267);
    }
}

$act = DeliveryActData::getById($_GET["id"]);
$client = PersonData::getById($act->person_id);
$us = UserData::getById($act->user_id);

$bill = $act->id;
$nbill = str_pad($act->id, 5, "0", STR_PAD_LEFT);
$sdate = $act->created_at;
$dia = date("d", strtotime($sdate));
$anio = date("Y", strtotime($sdate));
$mes = date("m", strtotime($sdate));
$total = 0;

$meses = array(
    "01" => "Enero", "02" => "Febrero", "03" => "Marzo",
    "04" => "Abril", "05" => "Mayo", "06" => "Junio",
    "07" => "Julio", "08" => "Agosto", "09" => "Septiembre",
    "10" => "Octubre", "11" => "Noviembre", "12" => "Diciembre"
);
$mesLetra = $meses[$mes] ?? "";

$pdf = new PDF("P", "mm", "letter");
$pdf->AliasNbPages();
$pdf->AddPage();
$widths = [20, 76, 22, 30, 23];
$pdf->SetXY(14, 115);
$pdf->SetFont("Arial", "B", 10);
$pdf->Cell($widths[0], 5, "CANT.", 0, 0, "C");
$pdf->Cell($widths[1], 5, "DESCRIPCION", 0, 0, "C");
$pdf->Cell($widths[2], 5, "UNID.", 0, 0, "C");
$pdf->Cell($widths[3], 5, "P. UNIT.", 0, 0, "C");
$pdf->Cell($widths[4], 5, "SUBTOTAL", 0, 1, "C");

$pdf->SetDrawColor(211, 211, 211);
$pdf->SetLineWidth(0.6);
$pdf->Line(14, 122, 200, 122);
$pdf->SetDrawColor(0, 0, 0);
$pdf->SetLineWidth(0.0);
$pdf->SetXY(10, 125);
$pdf->SetFont("Arial", "", 10);

$widths = [20, 76, 22, 30, 23];
$aligns = ["C", "L", "C", "R", "R"];

$total = 0;
$details = DeliveryActDetailData::getAllByAct($act->id);
foreach ($details as $d) {
    $quantity = (int)($d->quantity ?? 1);
    $text = utf8_decode(html_entity_decode($d->description ?? "", ENT_QUOTES, "UTF-8"));
    $unit = trim((string)($d->unit ?? "UNIDAD"));
    $unit_price = (float)($d->unit_price ?? 0);
    $subtotal = $quantity * $unit_price;

    $pdf->SetWidths($widths);
    $pdf->SetAligns($aligns);

    $pdf->Row(array(
        $quantity,
        $text,
        $unit,
        number_format($unit_price, 2, ".", ","),
        number_format($subtotal, 2, ".", ",")
    ));

    $pdf->SetXY($pdf->GetX(), $pdf->GetY() + 3);
    $total += $subtotal;
}

$pdf->SetFont("Arial", "B", 10);
$pdf->Cell(148, 0, "TOTAL Bs.", 0, 0, "R");
$pdf->Cell(23, 0, number_format(round($total, 0, PHP_ROUND_HALF_UP), 2, ".", ","), 0, 1, "R");

$pdf->Ln(10);
$pdf->SetX(14);
$pdf->SetFont("Arial", "B", 10);
$pdf->Cell(0, 8, mb_convert_encoding("DECLARACION:", "ISO-8859-1", "UTF-8"), 0, 1);
$pdf->SetFont("Arial", "", 10);
$pdf->SetX(14);
$declaration = isset($act->declaration) ? html_entity_decode($act->declaration, ENT_QUOTES, "UTF-8") : "Se hace constar que los productos/servicios detallados anteriormente fueron entregados y recibidos a satisfaccion del cliente en la fecha indicada.";
$pdf->MultiCell(186, 5, mb_convert_encoding($declaration, "ISO-8859-1", "UTF-8"), 0, "J");

$pdf->Ln(15);

// Firmas
$pdf->SetX(14);
$pdf->SetFont("Arial", "B", 10);
$pdf->Cell(80, 5, mb_convert_encoding("ENTREGADO POR:", "ISO-8859-1", "UTF-8"), 0, 0, "L");
$pdf->Cell(40, 5, "", 0, 0);
$pdf->Cell(80, 5, mb_convert_encoding("RECIBIDO POR:", "ISO-8859-1", "UTF-8"), 0, 1);

$pdf->Ln(10);
$pdf->SetX(14);
$pdf->SetFont("Arial", "", 9);
$pdf->Cell(80, 5, mb_convert_encoding("Nombre: " . ($us->name ?? "") . " " . ($us->lastname ?? ""), "ISO-8859-1", "UTF-8"), "T", 0, "L");
$pdf->Cell(40, 5, "", 0, 0);
$client_name = trim((string)($client->name_c ?? $client->name ?? ""));
$pdf->Cell(80, 5, mb_convert_encoding("Nombre: " . $client_name, "ISO-8859-1", "UTF-8"), "T", 1, "L");

$pdf->SetX(14);
$pdf->Cell(80, 5, mb_convert_encoding("Cargo: REPRESENTANTE TYKUN", "ISO-8859-1", "UTF-8"), "", 0, "L");
$pdf->Cell(40, 5, "", 0, 0);
$pdf->Cell(80, 5, mb_convert_encoding("Cargo:", "ISO-8859-1", "UTF-8"), "", 1, "L");

$pdf->SetX(14);
$pdf->Cell(80, 5, mb_convert_encoding("Fecha:", "ISO-8859-1", "UTF-8") . " " . date("d/m/Y"), "", 0, "L");
$pdf->Cell(40, 5, "", 0, 0);
$pdf->Cell(80, 5, mb_convert_encoding("Fecha:", "ISO-8859-1", "UTF-8") . " ___________________", "", 1, "L");

$pdf->Output("I", "acta_entrega.pdf");
exit;
