<?php
/**
 * ProposalCommercialPDF - Generador de PDF para propuestas comerciales
 */
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();
date_default_timezone_set("America/La_Paz");
include_once "core/autoload.php";
include_once "core/app/model/ProposalData.php";
include_once "core/app/model/ProposalSectionData.php";
include_once "core/app/model/PersonData.php";
include_once "core/app/model/ContactData.php";
include_once "core/app/model/UserData.php";
include_once "fpdf186/fpdf.php";

if (!isset($_GET["id"])) {
    die("ID de propuesta requerido");
}

$proposal_id = intval($_GET["id"]);
$proposal = ProposalData::getById($proposal_id);

if (!$proposal) {
    die("Propuesta no encontrada");
}

$client = PersonData::getById($proposal->client_id);
$contact = ContactData::getById($proposal->contact_id);
$sections = ProposalSectionData::getActiveByProposal($proposal->id);
$created_by = UserData::getById($proposal->created_by);

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

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

    function Row($data)
    {
        $nb = 0;
        for ($i = 0; $i < count($data); $i++)
            $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
        $h = 6 * $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, 6, $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'];
        $wmax = ($w - 2);
        $s = str_replace("\r", '', $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()
    {
        global $proposal;
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 8, utf8_decode("PROPUESTA COMERCIAL"), 0, 1, 'C');
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 6, utf8_decode(strtoupper($proposal->tipo_servicio)), 0, 1, 'C');
        $this->Ln(5);
    }

    function Footer()
    {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $id = isset($_GET["id"]) ? $_GET["id"] : "0";
        $this->Cell(0, 10, utf8_decode("TYKUN - Propuesta #" . $id) . " - Pagina " . $this->PageNo() . "/{nb}", 0, 0, 'C');
    }
}

$pdf = new ProposalPDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetAutoPageBreak(true, 15);

// ENCABEZADO CON LOGO
$pdf->SetFillColor(240, 240, 240);
$pdf->Rect(10, $pdf->GetY(), 190, 40, 'F');

$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(95, 10, utf8_decode("TYKUN"), 0, 0, 'L');
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(95, 10, utf8_decode("Consultora TYKUN"), 0, 1, 'R');

$pdf->SetX(10);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(95, 5, utf8_decode("La Paz, Bolivia"), 0, 0, 'L');
$fechaDisplay = $proposal->fecha ? date("d/m/Y", strtotime($proposal->fecha)) : date("d/m/Y");
$pdf->Cell(95, 5, utf8_decode("Fecha: " . $fechaDisplay), 0, 1, 'R');

$pdf->SetX(10);
$pdf->Cell(95, 5, utf8_decode("info@tykun.com"), 0, 0, 'L');
$pdf->Cell(95, 5, utf8_decode("Validez: " . $proposal->validez . " dias"), 0, 1, 'R');

$pdf->Ln(15);

// DATOS DEL CLIENTE
$pdf->SetFont('Arial', 'B', 11);
$pdf->Cell(0, 7, utf8_decode("DATOS DEL CLIENTE"), 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);

$clientName = $client ? $client->name . " " . $client->lastname : "No asignado";
$pdf->Cell(25, 6, utf8_decode("Cliente:"), 0, 0);
$pdf->Cell(80, 6, utf8_decode($clientName), 0, 0);

if ($contact) {
    $contactName = $contact->name . " " . $contact->lastname;
    $pdf->Cell(25, 6, utf8_decode("Contacto:"), 0, 0);
    $pdf->Cell(60, 6, utf8_decode($contactName), 0, 1);
} else {
    $pdf->Ln();
}

if ($proposal->place) {
    $pdf->Cell(25, 6, utf8_decode("Lugar:"), 0, 0);
    $pdf->Cell(0, 6, utf8_decode($proposal->place), 0, 1);
}

$pdf->Ln(10);

// SECCIONES
foreach ($sections as $sec) {
    if ($pdf->GetY() > 240) {
        $pdf->AddPage();
    }

    $pdf->SetFont('Arial', 'B', 12);
    $pdf->SetFillColor(220, 220, 220);
    $pdf->Cell(0, 8, utf8_decode($sec->title), 0, 1, 'L', true);
    $pdf->Ln(2);

    $pdf->SetFont('Arial', '', 10);
    $lines = explode("\n", $sec->content);
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) {
            $pdf->Ln(3);
            continue;
        }
        
        if (preg_match('/^[-*] (.*)$/', $line, $matches)) {
            $pdf->SetX(15);
            $pdf->Cell(5, 5, utf8_decode("*"), 0, 0);
            $pdf->MultiCell(175, 5, utf8_decode($matches[1]), 0, 'L');
        } else {
            $pdf->MultiCell(0, 5, utf8_decode($line), 0, 'J');
        }
    }
    
    $pdf->Ln(8);
}

// FIRMAS
if ($pdf->GetY() > 220) {
    $pdf->AddPage();
}

$pdf->Ln(10);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(0, 6, utf8_decode("ACEPTACION DE LA PROPUESTA"), 0, 1, 'L');
$pdf->SetFont('Arial', '', 10);

$pdf->Ln(5);
$pdf->Cell(95, 6, utf8_decode("Propuesta aceptada por:"), 0, 1);
$pdf->Ln(5);
$pdf->Cell(95, 6, utf8_decode("Nombre: ________________________"), 0, 0);
$pdf->Cell(95, 6, utf8_decode("Nombre: ________________________"), 0, 1);
$pdf->Ln(3);
$pdf->Cell(95, 6, utf8_decode("Fecha: ___/___/_______"), 0, 0);
$pdf->Cell(95, 6, utf8_decode("Firma: ________________________"), 0, 1);
$pdf->Ln(3);
$pdf->Cell(95, 6, utf8_decode("C.I.: ________________________"), 0, 1);

$pdf->Ln(10);
$pdf->SetFont('Arial', 'I', 9);
$pdf->SetTextColor(100, 100, 100);
$byName = $created_by ? $created_by->name . " " . $created_by->lastname : "TYKUN";
$pdf->Cell(0, 6, utf8_decode("Atendido por: " . $byName), 0, 1, 'R');

$filename = "Propuesta_Comercial_" . $proposal_id . "_" . date("Ymd") . ".pdf";
$pdf->Output("D", $filename);
