<?php
/**
 * credit_note_pdf.php - Fiscal Credit Note PDF
 *
 * Usage: credit_note_pdf.php?credit_note_id=12
 *
 * Mirrors fiscal_tax_invoice.php, titled "FISCAL CREDIT NOTE":
 *   - references the ORIGINAL invoice being credited (number + ZIMRA number)
 *   - shows the credited amount as a NEGATIVE figure (it reverses the invoice)
 *   - on a partial correction, states the replacement invoice raised
 *   - prints the ZIMRA block + QR code once the credit note is fiscalized
 */

require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$creditNoteId = (int)($_GET['credit_note_id'] ?? 0);
if ($creditNoteId <= 0) { http_response_code(400); exit('Invalid credit note.'); }

if (!function_exists('cnp_first_nonempty')) {
    function cnp_first_nonempty(array $row, array $candidates): string {
        foreach ($candidates as $c) {
            if (isset($row[$c]) && trim((string)$row[$c]) !== '') return trim((string)$row[$c]);
        }
        return '';
    }
}

$cn = $pdo->prepare("SELECT * FROM fdms_credit_notes WHERE id = :id LIMIT 1");
$cn->execute([':id' => $creditNoteId]);
$note = $cn->fetch(PDO::FETCH_ASSOC);
if (!$note) { http_response_code(404); exit('Credit note not found.'); }

$inv = $pdo->prepare("SELECT * FROM fdms_fiscal_invoices WHERE id = :id LIMIT 1");
$inv->execute([':id' => (int)$note['original_invoice_id']]);
$invoice = $inv->fetch(PDO::FETCH_ASSOC) ?: [];

$replacement = null;
if ((int)($note['replacement_invoice_id'] ?? 0) > 0) {
    $ri = $pdo->prepare("SELECT * FROM fdms_fiscal_invoices WHERE id = :id LIMIT 1");
    $ri->execute([':id' => (int)$note['replacement_invoice_id']]);
    $replacement = $ri->fetch(PDO::FETCH_ASSOC) ?: null;
}

$orderId = (int)$note['order_id'];
$o = $pdo->prepare("SELECT * FROM orders WHERE id = :oid LIMIT 1");
$o->execute([':oid' => $orderId]);
$order = $o->fetch(PDO::FETCH_ASSOC) ?: [];

$property = null;
try {
    $p = $pdo->prepare("SELECT * FROM properties WHERE id = :id LIMIT 1");
    $p->execute([':id' => (int)($order['property_id'] ?? 0)]);
    $property = $p->fetch(PDO::FETCH_ASSOC) ?: null;
} catch (Throwable $e) {}

/* Buyer + lines come straight from the ORIGINAL invoice's stored request,
   so the credit note reverses exactly what was invoiced. */
$origReq = json_decode((string)($invoice['request_json'] ?? ''), true);
$buyer = (is_array($origReq) && !empty($origReq['buyer'])) ? $origReq['buyer'] : [];
$lines = (is_array($origReq) && !empty($origReq['lines'])) ? $origReq['lines'] : [];

$currency = (string)($note['currency'] ?? 'USD');
$totalIncl = round((float)$note['amount_including_tax'], 2);
$vatRate = 15.5;
$vatAmount = round($totalIncl - ($totalIncl / (1 + ($vatRate / 100))), 2);
$netAmount = round($totalIncl - $vatAmount, 2);

$isFiscalized = ((int)($note['success'] ?? 0) === 1);
$isCorrection = ((string)($note['credit_type'] ?? 'full') === 'correction');

$propName    = $property ? cnp_first_nonempty($property, ['property_name', 'name', 'title']) : 'RoomZ Property';
$propAddress = $property ? cnp_first_nonempty($property, ['address', 'address1', 'physical_address']) : '';
$propVat     = $property ? cnp_first_nonempty($property, ['vat_no', 'vat_number', 'vatref']) : '';
$propTin     = $property ? cnp_first_nonempty($property, ['tin', 'tin_number', 'bp_no', 'bpno']) : '';
$propPhone   = $property ? cnp_first_nonempty($property, ['phone', 'tel', 'contact_no']) : '';
$propEmail   = $property ? cnp_first_nonempty($property, ['email']) : '';

$reasons = [1 => 'Cancellation of the transaction', 2 => 'Return of goods / services', 3 => 'Discount or price adjustment', 4 => 'Other correction'];
$reasonLabel = $reasons[(int)($note['reason_code'] ?? 4)] ?? 'Other correction';

$fpdfCandidates = [
    __DIR__ . '/../../includes/fpdf/fpdf.php',
    __DIR__ . '/../../includes/fpdf.php',
    __DIR__ . '/../../vendor/setasign/fpdf/fpdf.php',
    __DIR__ . '/../../libs/fpdf/fpdf.php',
];
if (!class_exists('FPDF')) {
    foreach ($fpdfCandidates as $cand) { if (is_file($cand)) { require_once $cand; break; } }
}
if (!class_exists('FPDF')) { http_response_code(500); exit('FPDF library not found.'); }

class CreditNotePDF extends FPDF
{
    public $propName = '';
    public $propAddress = '';
    public $propVat = '';
    public $propTin = '';
    public $propPhone = '';
    public $propEmail = '';
    public $notFiscalized = false;

    function Header()
    {
        if ($this->notFiscalized) {
            $this->SetFont('Arial', 'B', 44);
            $this->SetTextColor(240, 205, 205);
            $this->SetXY(12, 120);
            $this->Cell(186, 20, 'NOT YET FISCALIZED', 0, 0, 'C');
            $this->SetTextColor(0, 0, 0);
        }
        $this->SetFont('Arial', 'B', 15);
        $this->SetXY(10, 12);
        $this->Cell(120, 7, $this->propName, 0, 1, 'L');
        $this->SetFont('Arial', '', 8);
        if ($this->propAddress !== '') $this->Cell(120, 4, $this->propAddress, 0, 1, 'L');
        $meta = [];
        if ($this->propPhone !== '') $meta[] = 'Tel: ' . $this->propPhone;
        if ($this->propEmail !== '') $meta[] = $this->propEmail;
        if ($meta) $this->Cell(120, 4, implode('  |  ', $meta), 0, 1, 'L');
        $tax = [];
        if ($this->propVat !== '') $tax[] = 'VAT No: ' . $this->propVat;
        if ($this->propTin !== '') $tax[] = 'TIN/BP: ' . $this->propTin;
        if ($tax) $this->Cell(120, 4, implode('  |  ', $tax), 0, 1, 'L');

        $this->SetXY(130, 12);
        $this->SetFont('Arial', 'B', 14);
        $this->SetTextColor(20, 60, 140);
        $this->Cell(70, 8, 'FISCAL CREDIT NOTE', 0, 1, 'R');
        $this->SetTextColor(0, 0, 0);
        $this->Ln(3);
        $this->SetDrawColor(20, 60, 140);
        $this->SetLineWidth(0.6);
        $this->Line(10, $this->GetY(), 200, $this->GetY());
        $this->SetLineWidth(0.2);
        $this->SetDrawColor(0, 0, 0);
        $this->Ln(3);
    }

    function Footer()
    {
        $this->SetY(-14);
        $this->SetFont('Arial', 'I', 7);
        $this->SetTextColor(110, 110, 110);
        $this->Cell(0, 4, 'Page ' . $this->PageNo() . '/{nb}   -   Generated ' . date('d/m/Y H:i'), 0, 0, 'C');
        $this->SetTextColor(0, 0, 0);
    }

    function LabelValue(float $x, float $y, string $label, string $value, float $labelW = 30, float $valueW = 64): void
    {
        $this->SetXY($x, $y);
        $this->SetFont('Arial', 'B', 8);
        $this->Cell($labelW, 4.6, $label, 0, 0, 'L');
        $this->SetFont('Arial', '', 8);
        $this->Cell($valueW, 4.6, $value, 0, 1, 'L');
    }
}

$pdf = new CreditNotePDF('P', 'mm', 'A4');
$pdf->propName = $propName;
$pdf->propAddress = $propAddress;
$pdf->propVat = $propVat;
$pdf->propTin = $propTin;
$pdf->propPhone = $propPhone;
$pdf->propEmail = $propEmail;
$pdf->notFiscalized = !$isFiscalized;
$pdf->AliasNbPages();
$pdf->SetAutoPageBreak(true, 45);
$pdf->AddPage();

/* --- Credited-to + credit note details --- */
$top = $pdf->GetY() + 1;
$pdf->SetFont('Arial', 'B', 8.5);
$pdf->SetXY(10, $top);
$pdf->SetFillColor(242, 242, 242);
$pdf->Cell(92, 5, ' CREDITED TO', 1, 0, 'L', true);
$pdf->SetX(108);
$pdf->Cell(92, 5, ' CREDIT NOTE DETAILS', 1, 1, 'L', true);

$boxY = $pdf->GetY();
$pdf->SetFont('Arial', 'B', 9);
$pdf->SetXY(11, $boxY + 1.5);
$pdf->Cell(90, 5, (string)($buyer['name'] ?? 'Customer'), 0, 1, 'L');
$pdf->SetFont('Arial', '', 8);
foreach ([['address', ''], ['vatNumber', 'VAT No: '], ['tinNumber', 'TIN/BP No: ']] as $bf) {
    $val = trim((string)($buyer[$bf[0]] ?? ''));
    if ($val !== '') { $pdf->SetX(11); $pdf->Cell(90, 4.2, $bf[1] . $val, 0, 1, 'L'); }
}
$leftEnd = $pdf->GetY();

$y = $boxY + 1.5;
$pdf->LabelValue(109, $y, 'Credit Note No:', 'CN-' . $creditNoteId); $y += 4.6;
$pdf->LabelValue(109, $y, 'Date:', substr((string)$note['created_at'], 0, 10)); $y += 4.6;
$pdf->LabelValue(109, $y, 'Credits Invoice:', (string)$note['original_invoice_no']); $y += 4.6;
if (!empty($invoice['zimra_invoice_no'])) { $pdf->LabelValue(109, $y, 'Original ZIMRA No:', (string)$invoice['zimra_invoice_no']); $y += 4.6; }
$pdf->LabelValue(109, $y, 'Reason:', $reasonLabel); $y += 4.6;
$pdf->LabelValue(109, $y, 'Booking:', '#' . $orderId); $y += 4.6;
$pdf->LabelValue(109, $y, 'Currency:', $currency); $y += 4.6;
$rightEnd = $y;

$boxBottom = max($leftEnd, $rightEnd) + 1;
$pdf->Rect(10, $boxY, 92, $boxBottom - $boxY);
$pdf->Rect(108, $boxY, 92, $boxBottom - $boxY);
$pdf->SetY($boxBottom + 3);

/* --- Statement of what is being credited --- */
$pdf->SetFont('Arial', '', 8);
$pdf->SetFillColor(235, 241, 251);
$pdf->SetDrawColor(20, 60, 140);
$stmt = 'This credit note credits invoice ' . (string)$note['original_invoice_no'] . ' IN FULL ('
      . $currency . ' ' . number_format($totalIncl, 2) . ').';
if ($isCorrection && $replacement) {
    $stmt .= '  Replacement invoice ' . (string)$replacement['invoice_no'] . ' has been issued for '
           . $currency . ' ' . number_format((float)$replacement['amount_including_tax'], 2) . '.';
} elseif ($isCorrection) {
    $stmt .= '  A replacement invoice for ' . $currency . ' ' . number_format((float)($note['replacement_amount'] ?? 0), 2) . ' is pending.';
}
$pdf->MultiCell(190, 4.4, $stmt, 1, 'L', true);
$pdf->SetDrawColor(0, 0, 0);
$pdf->Ln(3);

/* --- Credited lines (negative) --- */
$pdf->SetFont('Arial', 'B', 8.5);
$pdf->SetFillColor(20, 60, 140);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(126, 6, ' Description', 1, 0, 'L', true);
$pdf->Cell(16, 6, 'Qty', 1, 0, 'C', true);
$pdf->Cell(24, 6, 'VAT %', 1, 0, 'C', true);
$pdf->Cell(24, 6, 'Amount ', 1, 1, 'R', true);
$pdf->SetTextColor(0, 0, 0);

$pdf->SetFont('Arial', '', 8);
$fill = false;
if ($lines) {
    foreach ($lines as $ln) {
        $qty = (int)($ln['quantity'] ?? 1);
        $lineTotal = round(((float)($ln['unitPriceIncludingTax'] ?? 0)) * $qty, 2);
        $desc = (string)($ln['description'] ?? 'Charge');
        if (strlen($desc) > 82) $desc = substr($desc, 0, 79) . '...';
        $pdf->SetFillColor(248, 248, 248);
        $pdf->Cell(126, 5.4, ' ' . $desc, 'LR', 0, 'L', $fill);
        $pdf->Cell(16, 5.4, (string)$qty, 'LR', 0, 'C', $fill);
        $pdf->Cell(24, 5.4, number_format((float)($ln['taxPercent'] ?? $vatRate), 1) . '%', 'LR', 0, 'C', $fill);
        $pdf->Cell(24, 5.4, '-' . number_format($lineTotal, 2) . ' ', 'LR', 1, 'R', $fill);
        $fill = !$fill;
    }
} else {
    $pdf->Cell(126, 5.4, ' Credit of invoice ' . (string)$note['original_invoice_no'], 'LR', 0, 'L');
    $pdf->Cell(16, 5.4, '1', 'LR', 0, 'C');
    $pdf->Cell(24, 5.4, number_format($vatRate, 1) . '%', 'LR', 0, 'C');
    $pdf->Cell(24, 5.4, '-' . number_format($totalIncl, 2) . ' ', 'LR', 1, 'R');
}
$pdf->Cell(190, 0, '', 'T', 1);

/* --- Totals (negative) --- */
$pdf->Ln(2);
$pdf->SetFont('Arial', '', 8.5);
$pdf->Cell(142, 5.2, '', 0, 0);
$pdf->Cell(24, 5.2, 'Net (excl VAT)', 0, 0, 'R');
$pdf->Cell(24, 5.2, '-' . number_format($netAmount, 2) . ' ', 0, 1, 'R');
$pdf->Cell(142, 5.2, '', 0, 0);
$pdf->Cell(24, 5.2, 'VAT @ ' . number_format($vatRate, 1) . '%', 0, 0, 'R');
$pdf->Cell(24, 5.2, '-' . number_format($vatAmount, 2) . ' ', 0, 1, 'R');

$pdf->SetFont('Arial', 'B', 9.5);
$pdf->SetFillColor(235, 235, 235);
$pdf->Cell(142, 6.4, '', 0, 0);
$pdf->Cell(24, 6.4, 'TOTAL CREDITED', 1, 0, 'R', true);
$pdf->Cell(24, 6.4, '-' . number_format($totalIncl, 2) . ' ', 1, 1, 'R', true);

/* --- ZIMRA block + QR --- */
$pdf->Ln(5);
if ($isFiscalized) {
    $blockY = $pdf->GetY();
    $pdf->SetFont('Arial', 'B', 8.5);
    $pdf->SetFillColor(242, 242, 242);
    $pdf->SetXY(10, $blockY);
    $pdf->Cell(190, 5, ' ZIMRA FISCALIZATION - CREDIT NOTE', 1, 1, 'L', true);
    $detailTop = $pdf->GetY();

    $y = $detailTop + 1.5;
    $pdf->LabelValue(11, $y, 'ZIMRA Credit Note No:', (string)($note['zimra_credit_no'] ?? ''), 38, 66); $y += 4.6;
    $pdf->LabelValue(11, $y, 'Verification Code:', (string)($note['verification_code'] ?? ''), 38, 66); $y += 4.6;
    $pdf->LabelValue(11, $y, 'Fiscal Day No:', (string)($note['fiscal_day_number'] ?? ''), 38, 66); $y += 4.6;
    $pdf->LabelValue(11, $y, 'Fiscal Device ID:', (string)($note['fiscal_device_id'] ?? ''), 38, 66); $y += 4.6;
    $pdf->LabelValue(11, $y, 'Fiscal Credit Note ID:', (string)($note['fiscal_id'] ?? ''), 38, 66); $y += 4.6;

    $qrUrl = trim((string)($note['qr_code_url'] ?? ''));
    $qrDrawn = false;
    if ($qrUrl !== '') {
        $qrX = 158; $qrY = $detailTop + 1.5; $qrSize = 30;
        $tmpFile = null;
        try {
            if (preg_match('/\.(png|jpg|jpeg|gif)(\?|$)/i', $qrUrl)) {
                $imgData = @file_get_contents($qrUrl);
                if ($imgData !== false && strlen($imgData) > 100) {
                    $ext = strtolower(preg_replace('/^.*\.([a-z]+)(\?.*)?$/i', '$1', $qrUrl));
                    if (!in_array($ext, ['png', 'jpg', 'jpeg', 'gif'], true)) $ext = 'png';
                    $tmpFile = sys_get_temp_dir() . '/rz_cnqr_' . $creditNoteId . '.' . $ext;
                    file_put_contents($tmpFile, $imgData);
                    $pdf->Image($tmpFile, $qrX, $qrY, $qrSize, $qrSize);
                    $qrDrawn = true;
                }
            }
            if (!$qrDrawn) {
                $gen = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . rawurlencode($qrUrl);
                $imgData = @file_get_contents($gen);
                if ($imgData !== false && strlen($imgData) > 100) {
                    $tmpFile = sys_get_temp_dir() . '/rz_cnqr_' . $creditNoteId . '.png';
                    file_put_contents($tmpFile, $imgData);
                    $pdf->Image($tmpFile, $qrX, $qrY, $qrSize, $qrSize);
                    $qrDrawn = true;
                }
            }
        } catch (Throwable $e) { $qrDrawn = false; }
        if ($tmpFile && is_file($tmpFile)) @unlink($tmpFile);

        if ($qrDrawn) {
            $pdf->SetFont('Arial', '', 6.5);
            $pdf->SetXY($qrX, $qrY + $qrSize + 0.5);
            $pdf->Cell($qrSize, 3.4, 'Scan to verify', 0, 0, 'C');
        } else {
            $pdf->SetFont('Arial', '', 6.5);
            $pdf->SetXY(11, $y);
            $pdf->MultiCell(140, 3.4, 'Verify at: ' . $qrUrl, 0, 'L');
            $y = $pdf->GetY();
        }
    }

    $blockBottom = max($y, $detailTop + 36) + 1;
    $pdf->Rect(10, $detailTop, 190, $blockBottom - $detailTop);
    $pdf->SetY($blockBottom + 3);

    $pdf->SetFont('Arial', 'I', 7);
    $pdf->SetTextColor(90, 90, 90);
    $pdf->Cell(0, 3.6, 'This is a fiscal credit note issued through the ZIMRA Fiscalisation Data Management System (FDMS).', 0, 1, 'C');
    $pdf->SetTextColor(0, 0, 0);
} else {
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->SetFillColor(253, 235, 235);
    $pdf->SetDrawColor(180, 60, 60);
    $pdf->SetTextColor(150, 20, 20);
    $pdf->Cell(190, 7, '  NOT YET FISCALIZED - this credit note was not accepted by ZIMRA. It is not valid until fiscalized.', 1, 1, 'L', true);
    $pdf->SetTextColor(0, 0, 0);
    $pdf->SetDrawColor(0, 0, 0);
}

$pdf->Output('I', 'Credit_Note_CN-' . $creditNoteId . '.pdf');
