<?php
require_once __DIR__ . '/SimplePDF.php';
require_once __DIR__ . '/functions.php';

/**
 * DocumentPDF - Generates PDFs for Quotation, Delivery Note, Tax Invoice
 * Uses SimplePDF (pure PHP, no external libraries)
 */
class DocumentPDF {

    private static function getCompany() {
        return [
            'name'    => getSetting('company_name', 'Your Company'),
            'address' => getSetting('company_address', ''),
            'gst'     => getSetting('company_gst', ''),
            'phone'   => getSetting('company_phone', ''),
            'email'   => getSetting('company_email', ''),
        ];
    }

    // ── QUOTATION PDF ─────────────────────────────────────────
    public static function quotation($quotationId, $dest = 'D') {
        global $pdo;
        $co = self::getCompany();

        $stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email, c.phone,
                                c.billing_address, c.city, c.state, c.pincode, c.gst_number
                                FROM quotations q JOIN sale_vendors c ON c.id=q.customer_id
                                WHERE q.id=?");
        $stmt->execute([$quotationId]);
        $q = $stmt->fetch();
        if (!$q) return false;

        $stmt = $pdo->prepare("SELECT qi.*, i.item_name, i.hsn_code, i.unit
                                FROM quotation_items qi JOIN items i ON i.id=qi.item_id
                                WHERE qi.quotation_id=? ORDER BY qi.id");
        $stmt->execute([$quotationId]);
        $items = $stmt->fetchAll();

        $pdf = new SimplePDF();
        $pdf->addHeader($co['name'], 'QUOTATION', $q['quotation_no'],
            date('d-M-Y', strtotime($q['quotation_date'])),
            date('d-M-Y', strtotime($q['valid_until'])));
        $pdf->addCompanyDetails($co['address'], $co['gst'], $co['phone'], $co['email']);
        $pdf->addPartyBox('To', $q['customer_name'],
            $q['billing_address'] ?? '', $q['city'] ?? '', $q['state'] ?? '',
            $q['phone'], $q['gst_number'] ?? '');

        // Items table
        $cols = [
            ['label'=>'#',           'width'=>18,  'align'=>'L'],
            ['label'=>'Item',        'width'=>150, 'align'=>'L'],
            ['label'=>'HSN',         'width'=>55,  'align'=>'L'],
            ['label'=>'Qty',         'width'=>30,  'align'=>'R'],
            ['label'=>'Rate',        'width'=>55,  'align'=>'R'],
            ['label'=>'CGST',        'width'=>50,  'align'=>'R'],
            ['label'=>'SGST',        'width'=>50,  'align'=>'R'],
            ['label'=>'Amount',      'width'=>57,  'align'=>'R'],
        ];
        $pdf->addSectionTitle('Items');
        $pdf->addTableHeader($cols);

        $subTotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        foreach ($items as $idx => $li) {
            $original = $li['line_total_before_discount'] ?: 0;
            $ratio    = $original > 0 ? $li['line_final_amount'] / $original : 1;
            $base     = round($li['line_subtotal'] * $ratio, 2);
            $cgst     = round($li['line_cgst'] * $ratio, 2);
            $sgst     = round($li['line_sgst'] * $ratio, 2);
            $rate     = $li['qty'] > 0 ? $base / $li['qty'] : 0;
            $subTotal += $base; $cgstTotal += $cgst; $sgstTotal += $sgst;
            $pdf->addTableRow($cols, [
                $idx + 1,
                mb_substr($li['item_name'], 0, 30),
                $li['hsn_code'] ?? '-',
                $li['qty'],
                'Rs.' . number_format($rate, 2),
                'Rs.' . number_format($cgst, 2),
                'Rs.' . number_format($sgst, 2),
                'Rs.' . number_format($li['line_final_amount'], 2),
            ]);
        }

        $pdf->addTotalsBox([
            ['label'=>'Subtotal',    'value'=>'Rs.' . number_format($subTotal, 2)],
            ['label'=>'CGST',        'value'=>'Rs.' . number_format($cgstTotal, 2)],
            ['label'=>'SGST',        'value'=>'Rs.' . number_format($sgstTotal, 2)],
            ['label'=>'Grand Total', 'value'=>'Rs.' . number_format($q['grand_total'], 2), 'bold'=>true],
        ]);

        if ($q['notes']) $pdf->addNote('Notes', $q['notes']);
        $pdf->addFooter('This is a system-generated quotation. Prices inclusive of applicable taxes.');

        return $pdf->output('Quotation_' . $q['quotation_no'] . '.pdf', $dest);
    }

    // ── DELIVERY NOTE PDF ─────────────────────────────────────
    public static function deliveryNote($deliveryId, $dest = 'D') {
        global $pdo;
        $co = self::getCompany();

        $stmt = $pdo->prepare("SELECT d.*, c.customer_name, c.email, c.phone,
                                c.shipping_address, c.billing_address, c.city, c.state, c.pincode,
                                q.quotation_no, q.id as q_id
                                FROM delivery_notes d
                                JOIN sale_vendors c ON c.id=d.customer_id
                                JOIN quotations q ON q.id=d.quotation_id
                                WHERE d.id=?");
        $stmt->execute([$deliveryId]);
        $d = $stmt->fetch();
        if (!$d) return false;

        $stmt = $pdo->prepare("SELECT dni.qty, i.item_name, i.item_code, i.unit,
                                qi.unit_price, qi.cgst_percent, qi.sgst_percent,
                                qi.line_subtotal, qi.line_cgst, qi.line_sgst,
                                qi.line_total_before_discount, qi.line_final_amount
                                FROM delivery_note_items dni
                                JOIN items i ON i.id=dni.item_id
                                LEFT JOIN quotation_items qi ON qi.quotation_id=:qid AND qi.item_id=dni.item_id
                                WHERE dni.delivery_note_id=:did");
        $stmt->execute(['qid'=>$d['q_id'], 'did'=>$deliveryId]);
        $items = $stmt->fetchAll();

        $pdf = new SimplePDF();
        $pdf->addHeader($co['name'], 'DELIVERY NOTE', $d['delivery_no'],
            date('d-M-Y', strtotime($d['delivery_date'])));
        $pdf->addCompanyDetails($co['address'], $co['gst'], $co['phone'], $co['email']);
        $pdf->addPartyBox('Deliver To', $d['customer_name'],
            $d['shipping_address'] ?? $d['billing_address'] ?? '',
            $d['city'] ?? '', $d['state'] ?? '', $d['phone']);

        $cols = [
            ['label'=>'#',       'width'=>18,  'align'=>'L'],
            ['label'=>'Item',    'width'=>180, 'align'=>'L'],
            ['label'=>'Code',    'width'=>60,  'align'=>'L'],
            ['label'=>'Qty',     'width'=>35,  'align'=>'R'],
            ['label'=>'Rate',    'width'=>55,  'align'=>'R'],
            ['label'=>'CGST',    'width'=>52,  'align'=>'R'],
            ['label'=>'SGST',    'width'=>52,  'align'=>'R'],
            ['label'=>'Amount',  'width'=>63,  'align'=>'R'],
        ];
        $pdf->addSectionTitle('Items');
        $pdf->addTableHeader($cols);

        $subTotal = 0; $cgstTotal = 0; $sgstTotal = 0;
        foreach ($items as $idx => $li) {
            $original = $li['line_total_before_discount'] ?: 0;
            $ratio    = $original > 0 ? $li['line_final_amount'] / $original : 1;
            $base     = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
            $cgst     = round(($li['line_cgst'] ?? 0) * $ratio, 2);
            $sgst     = round(($li['line_sgst'] ?? 0) * $ratio, 2);
            $rate     = $li['qty'] > 0 ? $base / $li['qty'] : 0;
            $subTotal += $base; $cgstTotal += $cgst; $sgstTotal += $sgst;
            $pdf->addTableRow($cols, [
                $idx + 1,
                mb_substr($li['item_name'], 0, 35),
                $li['item_code'],
                $li['qty'],
                'Rs.' . number_format($rate, 2),
                'Rs.' . number_format($cgst, 2),
                'Rs.' . number_format($sgst, 2),
                'Rs.' . number_format($base + $cgst + $sgst, 2),
            ]);
        }

        $total = $subTotal + $cgstTotal + $sgstTotal;
        $pdf->addTotalsBox([
            ['label'=>'Subtotal',     'value'=>'Rs.' . number_format($subTotal, 2)],
            ['label'=>'CGST',         'value'=>'Rs.' . number_format($cgstTotal, 2)],
            ['label'=>'SGST',         'value'=>'Rs.' . number_format($sgstTotal, 2)],
            ['label'=>'Total Amount', 'value'=>'Rs.' . number_format($total, 2), 'bold'=>true],
        ]);

        if ($d['notes']) $pdf->addNote('Instructions', $d['notes']);
        $pdf->addNote('Ref Quotation', $d['quotation_no']);
        $pdf->addFooter('Please verify quantities upon receipt. Tax Invoice will follow separately.');

        return $pdf->output('DeliveryNote_' . $d['delivery_no'] . '.pdf', $dest);
    }

    // ── TAX INVOICE PDF ───────────────────────────────────────
    public static function taxInvoice($invoiceId, $dest = 'D') {
        global $pdo;
        $co = self::getCompany();

        $stmt = $pdo->prepare("SELECT i.*, c.customer_name, c.email, c.phone,
                                c.billing_address, c.city, c.state, c.pincode, c.gst_number
                                FROM invoices i JOIN sale_vendors c ON c.id=i.customer_id
                                WHERE i.id=?");
        $stmt->execute([$invoiceId]);
        $inv = $stmt->fetch();
        if (!$inv) return false;

        $stmt = $pdo->prepare("SELECT ii.*, COALESCE(i.item_name, ii.description) item_label,
                                i.hsn_code, i.unit
                                FROM invoice_items ii
                                LEFT JOIN items i ON i.id=ii.item_id
                                WHERE ii.invoice_id=?");
        $stmt->execute([$invoiceId]);
        $items = $stmt->fetchAll();

        $pdf = new SimplePDF();
        $pdf->addHeader($co['name'], 'TAX INVOICE', $inv['invoice_no'],
            date('d-M-Y', strtotime($inv['invoice_date'])));
        $pdf->addCompanyDetails($co['address'], $co['gst'], $co['phone'], $co['email']);
        $pdf->addPartyBox('Bill To', $inv['customer_name'],
            $inv['billing_address'] ?? '', $inv['city'] ?? '', $inv['state'] ?? '',
            $inv['phone'], $inv['gst_number'] ?? '');

        $cols = [
            ['label'=>'#',       'width'=>18,  'align'=>'L'],
            ['label'=>'Item',    'width'=>150, 'align'=>'L'],
            ['label'=>'HSN',     'width'=>50,  'align'=>'L'],
            ['label'=>'Qty',     'width'=>30,  'align'=>'R'],
            ['label'=>'Rate',    'width'=>60,  'align'=>'R'],
            ['label'=>'CGST',    'width'=>55,  'align'=>'R'],
            ['label'=>'SGST',    'width'=>55,  'align'=>'R'],
            ['label'=>'Amount',  'width'=>57,  'align'=>'R'],
        ];
        $pdf->addSectionTitle('Items');
        $pdf->addTableHeader($cols);

        foreach ($items as $idx => $li) {
            $rate = $li['qty'] > 0 ? $li['line_subtotal'] / $li['qty'] : 0;
            $pdf->addTableRow($cols, [
                $idx + 1,
                mb_substr($li['item_label'] ?? $li['description'], 0, 30),
                $li['hsn_code'] ?? '-',
                number_format($li['qty'], 0),
                'Rs.' . number_format($rate, 2),
                'Rs.' . number_format($li['line_cgst'], 2) . ' (' . $li['cgst_percent'] . '%)',
                'Rs.' . number_format($li['line_sgst'], 2) . ' (' . $li['sgst_percent'] . '%)',
                'Rs.' . number_format($li['line_total'], 2),
            ]);
        }

        $totalsRows = [
            ['label'=>'Subtotal', 'value'=>'Rs.' . number_format($inv['subtotal'], 2)],
            ['label'=>'CGST',     'value'=>'Rs.' . number_format($inv['cgst_amount'], 2)],
            ['label'=>'SGST',     'value'=>'Rs.' . number_format($inv['sgst_amount'], 2)],
        ];
        if ($inv['tds_amount'] > 0) {
            $totalsRows[] = ['label'=>'TDS Deducted', 'value'=>'Rs.' . number_format($inv['tds_amount'], 2)];
        }
        $totalsRows[] = ['label'=>'Grand Total', 'value'=>'Rs.' . number_format($inv['grand_total'], 2), 'bold'=>true];

        $pdf->addTotalsBox($totalsRows);

        // Payment status
        if ($inv['payment_status'] === 'paid') {
            $pdf->addNote('Payment Status', 'PAID on ' . date('d-M-Y', strtotime($inv['payment_date'])) . ' via ' . $inv['payment_mode']);
        } elseif ($inv['payment_status'] === 'partial') {
            $balance = $inv['grand_total'] - $inv['paid_amount'] - $inv['tds_amount'];
            $pdf->addNote('Payment Status', 'Partial - Balance Due: Rs.' . number_format($balance, 2));
        } else {
            $pdf->addNote('Payment Status', 'PENDING - Rs.' . number_format($inv['grand_total'], 2) . ' due');
        }

        $pdf->addFooter('This is a computer-generated invoice. No signature required.');

        return $pdf->output('Invoice_' . $inv['invoice_no'] . '.pdf', $dest);
    }

    // ── Save PDF to temp file (for email attachment) ──────────
    public static function saveTemp($type, $id) {
        $tmpDir = sys_get_temp_dir();
        $tmpFile = $tmpDir . DIRECTORY_SEPARATOR . $type . '_' . $id . '_' . time() . '.pdf';

        switch ($type) {
            case 'quotation':     return self::quotation($id, $tmpFile);
            case 'delivery_note': return self::deliveryNote($id, $tmpFile);
            case 'invoice':       return self::taxInvoice($id, $tmpFile);
        }
        return false;
    }
}
