<?php
/**
 * generate_assignment.php
 * Pure PHP PDF — matches the Word template design exactly.
 * Two-column layout for customer/company info and signatures.
 */

class AssignmentPDF {
    private $pages = [];
    private $cp = -1;
    private $y = 0;
    private $pH = 841.89; // A4
    private $pW = 595.28;
    private $mL = 42;
    private $mR = 42;
    private $fS = 10;
    private $fSt = '';
    private $tC = '0 0 0';
    
    public function addPage() {
        $this->pages[] = '';
        $this->cp = count($this->pages) - 1;
        $this->y = $this->pH - 30;
    }
    
    public function setFont($size, $style = '') { $this->fS = $size; $this->fSt = $style; }
    public function setColor($r, $g, $b) { $this->tC = sprintf('%.3f %.3f %.3f', $r/255, $g/255, $b/255); }
    public function getY() { return $this->y; }
    public function setY($y) { $this->y = $y; }
    
    private function fn() {
        $b = strpos($this->fSt, 'B') !== false;
        $i = strpos($this->fSt, 'I') !== false;
        if ($b && $i) return 'F4';
        if ($b) return 'F2';
        if ($i) return 'F3';
        return 'F1';
    }
    
    private function esc($s) {
        $s = @iconv('UTF-8', 'Windows-1252//TRANSLIT//IGNORE', $s) ?: $s;
        return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $s);
    }
    
    // Approximate char width for Helvetica
    private function cw() {
        $base = $this->fS * 0.48;
        if (strpos($this->fSt, 'B') !== false) $base *= 1.05;
        if (strpos($this->fSt, 'I') !== false) $base *= 0.97;
        return $base;
    }
    
    private function wrap($text, $maxW) {
        $mc = max(1, floor($maxW / $this->cw()));
        $words = explode(' ', $text);
        $lines = []; $line = '';
        foreach ($words as $w) {
            $t = $line ? "$line $w" : $w;
            if (strlen($t) > $mc && $line !== '') { $lines[] = $line; $line = $w; }
            else $line = $t;
        }
        if ($line) $lines[] = $line;
        return $lines;
    }
    
    // Put text at absolute position (does NOT move Y)
    public function textAt($x, $y, $text) {
        $fn = $this->fn();
        $this->pages[$this->cp] .= "BT /{$fn} {$this->fS} Tf {$this->tC} rg 1 0 0 1 {$x} {$y} Tm ({$this->esc($text)}) Tj ET\n";
    }
    
    // Draw line
    public function line($x1, $y1, $x2, $y2, $width = 0.5) {
        $this->pages[$this->cp] .= "{$width} w 0.75 0.75 0.75 RG {$x1} {$y1} m {$x2} {$y2} l S\n";
    }
    
    // Write line at current Y, then move Y down
    public function wl($text, $x = null, $lh = null) {
        if ($x === null) $x = $this->mL;
        if ($lh === null) $lh = $this->fS * 1.4;
        $this->textAt($x, $this->y, $text);
        $this->y -= $lh;
        if ($this->y < 30) $this->addPage();
    }
    
    // Write wrapped at current Y
    public function ww($text, $x = null, $maxW = null, $lh = null) {
        if ($x === null) $x = $this->mL;
        if ($maxW === null) $maxW = $this->pW - $this->mL - $this->mR;
        if ($lh === null) $lh = $this->fS * 1.35;
        foreach ($this->wrap($text, $maxW) as $line) {
            $this->textAt($x, $this->y, $line);
            $this->y -= $lh;
            if ($this->y < 30) $this->addPage();
        }
    }
    
    // Write wrapped at specific position (does NOT change Y), returns lines used
    public function wwAt($x, $y, $text, $maxW, $lh = null) {
        if ($lh === null) $lh = $this->fS * 1.35;
        $lines = $this->wrap($text, $maxW);
        foreach ($lines as $i => $line) {
            $this->textAt($x, $y - ($i * $lh), $line);
        }
        return count($lines);
    }
    
    public function ln($h = null) {
        $this->y -= ($h ?? $this->fS * 1.2);
        if ($this->y < 30) $this->addPage();
    }
    
    // Store images for embedding in PDF
    private $images = [];
    
    // Place a JPEG image at absolute position
    public function placeImage($path, $x, $y, $w, $h) {
        $data = file_get_contents($path);
        if (!$data) return;
        $info = getimagesize($path);
        if (!$info) return;
        $imgW = $info[0]; $imgH = $info[1];
        $this->images[] = ['data' => $data, 'w' => $imgW, 'h' => $imgH, 'page' => $this->cp];
        $imgIdx = count($this->images) - 1;
        // PDF image placement: save state, transform, draw, restore
        $this->pages[$this->cp] .= "q {$w} 0 0 {$h} {$x} {$y} cm /Img{$imgIdx} Do Q\n";
    }
    
    public function output($path) {
        $objs = [];
        $n = 0;
        $objs[++$n] = "<< /Type /Catalog /Pages 2 0 R >>";
        $pObj = ++$n;
        $fonts = ['Helvetica'=>++$n, 'Helvetica-Bold'=>++$n, 'Helvetica-Oblique'=>++$n, 'Helvetica-BoldOblique'=>++$n];
        foreach ($fonts as $fname => $fnum) {
            $objs[$fnum] = "<< /Type /Font /Subtype /Type1 /BaseFont /$fname /Encoding /WinAnsiEncoding >>";
        }
        $fr = "/F1 {$fonts['Helvetica']} 0 R /F2 {$fonts['Helvetica-Bold']} 0 R /F3 {$fonts['Helvetica-Oblique']} 0 R /F4 {$fonts['Helvetica-BoldOblique']} 0 R";
        
        // Build image objects
        $imgRefs = [];
        foreach ($this->images as $idx => $img) {
            $imgObjN = ++$n;
            $imgRefs[$idx] = $imgObjN;
            $objs[$imgObjN] = "img_stream_{$idx}"; // placeholder
        }
        
        // Build image resource string per page
        $pageImgRes = [];
        foreach ($this->images as $idx => $img) {
            $p = $img['page'];
            if (!isset($pageImgRes[$p])) $pageImgRes[$p] = '';
            $pageImgRes[$p] .= " /Img{$idx} {$imgRefs[$idx]} 0 R";
        }
        
        $pNums = [];
        foreach ($this->pages as $pi => $content) {
            $pNum = ++$n; $sNum = ++$n;
            $pNums[] = $pNum;
            $xobjStr = isset($pageImgRes[$pi]) ? " /XObject <<{$pageImgRes[$pi]} >>" : '';
            $objs[$pNum] = "<< /Type /Page /Parent $pObj 0 R /MediaBox [0 0 {$this->pW} {$this->pH}] /Contents $sNum 0 R /Resources << /Font << $fr >>{$xobjStr} >> >>";
            $objs[$sNum] = "stream\n$content";
        }
        $kids = implode(' ', array_map(function($p){return "$p 0 R";}, $pNums));
        $objs[$pObj] = "<< /Type /Pages /Kids [ $kids ] /Count " . count($pNums) . " >>";
        
        $out = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
        $off = [];
        for ($i = 1; $i <= $n; $i++) {
            $off[$i] = strlen($out);
            $o = $objs[$i];
            // Check if this is an image stream placeholder
            if (strpos($o, 'img_stream_') === 0) {
                $imgIdx = intval(substr($o, 11));
                $img = $this->images[$imgIdx];
                $imgData = $img['data'];
                $l = strlen($imgData);
                $out .= "$i 0 obj\n<< /Type /XObject /Subtype /Image /Width {$img['w']} /Height {$img['h']} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length $l >>\nstream\n{$imgData}\nendstream\nendobj\n";
            } elseif (strpos($o, 'stream') === 0) {
                $s = substr($o, 7); $l = strlen($s);
                $out .= "$i 0 obj\n<< /Length $l >>\nstream\n{$s}endstream\nendobj\n";
            } else $out .= "$i 0 obj\n$o\nendobj\n";
        }
        $xr = strlen($out); $tot = $n + 1;
        $out .= "xref\n0 $tot\n0000000000 65535 f \n";
        for ($i = 1; $i <= $n; $i++) $out .= sprintf("%010d 00000 n \n", $off[$i]);
        $out .= "trailer\n<< /Size $tot /Root 1 0 R >>\nstartxref\n$xr\n%%EOF\n";
        file_put_contents($path, $out);
        return true;
    }
}

function generateAssignment($pdo, $customerId, $uploadDir, $templatePath) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$customerId]);
    $c = $stmt->fetch();
    if (!$c) return false;

    $name = $c['first_name'] . ' ' . $c['last_name'];
    $bk = $c['booking_ref'];
    $street = trim($c['address_street'] ?? '');
    $city = trim($c['address_city'] ?? '');
    $postal = trim($c['address_postal'] ?? '');
    $country = trim($c['address_country'] ?? '');
    $addr = implode(', ', array_filter([$street, $postal, $city, $country]));
    $today = date('Y-m-d');
    if (!$addr) return false;

    $pdf = new AssignmentPDF();
    $pdf->addPage();
    
    $L = 42;       // left margin
    $R = 310;      // right column start
    $cW = 255;     // column width
    $bW = 510;     // body width
    $lh10 = 13;    // line height for 10pt
    $lh9 = 12;     // line height for 9pt
    $lh8 = 10.5;   // line height for 8pt

    // ===== HEADER ROW (two-column with line) =====
    $y = $pdf->getY();
    
    $pdf->setFont(9, ''); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $y, 'EN');
    
    $pdf->setFont(11, 'B'); $pdf->setColor(0,0,0);
    $pdf->textAt(210, $y, 'Assignment Agreement');
    
    // Horizontal separator line
    $y -= 18;
    $pdf->line($L, $y, $L + $bW, $y, 0.5);
    $y -= 14;
    $pdf->setY($y);

    // ===== TWO-COLUMN: CUSTOMER (left) + COMPANY (right) =====
    $colTop = $y;
    
    // --- LEFT COLUMN: Customer ---
    $ly = $colTop;
    
    $pdf->setFont(9, 'B'); $pdf->setColor(0,0,0);
    $pdf->textAt($L, $ly, '"Customer" or "Assignor"');
    $ly -= $lh9 + 4;
    
    $pdf->setFont(10, 'B'); $pdf->setColor(91,155,213);
    $pdf->textAt($L, $ly, $name);
    $ly -= $lh10;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $ly, 'Complete name');
    $ly -= $lh8 + 4;
    
    $pdf->setFont(10, 'B'); $pdf->setColor(91,155,213);
    $pdf->textAt($L, $ly, $bk);
    $ly -= $lh10;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $ly, 'Booking ref.');
    $ly -= $lh8 + 4;
    
    $pdf->setFont(10, 'B'); $pdf->setColor(91,155,213);
    $pdf->setY($ly);
    $addrLines = $pdf->wwAt($L, $ly, $addr, $cW, $lh10);
    $ly -= $addrLines * $lh10;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $ly, 'Address of domicile');
    $ly -= $lh8;
    $leftBottom = $ly;
    
    // --- RIGHT COLUMN: Company ---
    $ry = $colTop;
    
    $pdf->setFont(9, 'B'); $pdf->setColor(0,0,0);
    $pdf->textAt($R, $ry, '"Smart Solution, UAB" or "Assignee"');
    $ry -= $lh9 + 4;
    
    $pdf->setFont(8, ''); $pdf->setColor(0,0,0);
    $companyText = 'SMART SOLUTION UAB, a Lithuanian company with Tax registration no.: 305644774, Managing Directors: Marijus Jagusinskis, Corporate address: Architektu g. 152B, Vilnius';
    $compLines = $pdf->wwAt($R, $ry, $companyText, $cW, $lh8);
    $ry -= $compLines * $lh8;
    $rightBottom = $ry;
    
    // Move Y below both columns
    $y = min($leftBottom, $rightBottom) - 12;
    $pdf->setY($y);
    
    // ===== BODY TEXT =====
    $pdf->setFont(9, 'B'); $pdf->setColor(0,0,0);
    $pdf->wl('By signing this document, both parties agree to the following:', $L, $lh9);
    $pdf->ln(4);
    
    $pdf->setFont(8, ''); $pdf->setColor(0,0,0);

    $clauses = [
        '1. The Customer hereby assigns and transfers full ownership of their Claim to SMART SOLUTION, UAB. This assignment includes the Customer\'s legal rights to claim for compensation due to financial loss, damages, or reimbursement under Regulation (EC) No. 261/2004, UK Air Passenger Rights Law ("UK261"), the Montreal Convention of 1999 (MC99), the Brazilian Consumer Code and Brazilian Aeronautical Code, Turkish "SHY" passenger regulation, Canadian Transportation Act: Air Passenger Protection Regulations, or gesture of goodwill, arising from the disrupted flight(s) identified by the above mentioned booking reference (i.e. the "Claim").',
        '2. SMART SOLUTION, UAB accepts this transfer and hereby acquires the Customer\'s rights to the Claim, agreeing to act against third parties with all rights and obligations.',
        '3. This Assignment Agreement is made in accordance with the SMART SOLUTION, UAB Terms and Conditions and Our Fees, which have already been read and accepted by the Customer at DeelayHelp.com.',
        '4. This Assignment Agreement entitles SMART SOLUTION, UAB to the same rights and powers the Customer previously held within the scope of the Claim. Specifically, SMART SOLUTION, UAB is entitled to:',
    ];
    foreach ($clauses as $t) { $pdf->ww($t, $L, $bW, $lh8); $pdf->ln(3); }

    $subs = [
        'a. Act before any third parties in all both amicable and judicial proceedings, in any instance.',
        'b. Initiate, submit, and terminate any legal and extrajudicial proceeding related to the Claim (either individually or as a collective with other customers).',
        'c. Obtain information required from third parties, including administrative bodies responsible for enforcing air passenger rights regulations, where permitted by civil and administrative laws.',
        'd. Collect, recover, and receive all payments related to the Claim into the bank account that SMART SOLUTION, UAB appoints, into which the Debtor must make all payments. This includes but is not limited to: compensation, interests, fees, and any legal costs from the operating carrier (or "Debtor") and/or the courts.',
        'e. Appoint and mandate any law firm, solicitor or counsel to represent and assist SMART SOLUTION, UAB in all amicable and judicial proceedings in connection with the Claim.',
    ];
    foreach ($subs as $t) { $pdf->ww($t, $L + 25, $bW - 25, $lh8); $pdf->ln(2); }

    $more = [
        '5. This Assignment Agreement shall be effective as of the date the Customer signs it and shall be used as notification in writing to any third party, including the operating carrier. When such notification is legally mandatory, the third party shall consider this Assignment Agreement effective from the date of the notification. This Assignment Agreement can also include the documents "Claim-PDF" (a payment request from SMART SOLUTION, UAB to the operating carrier) and SMART SOLUTION, UAB\'s Electronic Signature Certificate (also known as the "Certificate of Completion").',
        '6. The Customer hereby affirms that they have not assigned the Claim to any other third party prior to this Assignment Agreement. The Customer understands that they may not assign the Claim again, assert the Claim in their own name, or accept any direct contact or payment from the operating carrier.',
        '7. The Customer authorizes SMART SOLUTION, UAB to request that any third party only process the Customer\'s personal data for the purpose of verifying and resolving the Claim, according to applicable data protection laws.',
        '8. In accordance with Article 9.10 of SMART SOLUTION, UAB\'s Terms and Conditions, the laws of Lithuania apply to this document and any dispute related to its interpretation or validity.',
        '9. If this Assignment Agreement is written in two languages, the English language version shall prevail in the case of any inconsistencies.',
    ];
    foreach ($more as $t) { $pdf->ww($t, $L, $bW, $lh8); $pdf->ln(3); }

    $pdf->ln(8);

    // ===== SIGNATURE AREA (two columns) =====
    // Extra space before signatures for breathing room
    $pdf->ln(40);
    
    $sigTop = $pdf->getY();
    
    // --- Left: Customer signature ---
    $sy = $sigTop;
    
    // Signature space
    $sy -= 30;
    
    $sy -= 12;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $sy, 'Customer\'s Signature');
    $sy -= $lh8 + 6;
    
    $pdf->setFont(10, 'B'); $pdf->setColor(91,155,213);
    $pdf->textAt($L, $sy, $name);
    $sy -= $lh10;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $sy, 'Complete name');
    $sy -= $lh8 + 6;
    
    $pdf->setFont(10, 'B'); $pdf->setColor(91,155,213);
    $pdf->textAt($L, $sy, $today);
    $sy -= $lh10;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($L, $sy, 'Date');
    
    // --- Right: Company signature ---
    $sy2 = $sigTop;
    
    // Same signature space as left
    $sy2 -= 30;
    
    // Place signature image
    $sigImgPath = __DIR__ . '/signature.jpg';
    if (file_exists($sigImgPath)) {
        $sigImgW = 150;
        $sigImgH = 42;
        $imgX = $R + 5;
        $imgY = $sy2 - 2; // bottom of image sits on the line, image extends upward
        $pdf->placeImage($sigImgPath, $imgX, $imgY, $sigImgW, $sigImgH);
    }
    
    $sy2 -= 12;
    
    $pdf->setFont(8, ''); $pdf->setColor(0,0,0);
    // Empty line for signature space
    $sy2 -= $lh8 + 6;
    
    $pdf->setFont(9, ''); $pdf->setColor(0,0,0);
    $pdf->textAt($R, $sy2, 'Marijus Jagusinskis');
    $sy2 -= $lh9;
    
    $pdf->setFont(8, 'I'); $pdf->setColor(102,102,102);
    $pdf->textAt($R, $sy2, 'Authorized signatory - SMART SOLUTION, UAB');

    // ===== SAVE =====
    $fn = $c['customer_id'] . '_assignment_' . time() . '.pdf';
    $fp = $uploadDir . $fn;
    $pdf->output($fp);

    $pdo->prepare("UPDATE customers SET assignment_filename=?, assignment_path=?, updated_at=NOW() WHERE id=?")
        ->execute(['Assignment_' . $name . '.pdf', $fn, $customerId]);

    return $fn;
}