<?php
require_once '../includes/auth.php';
requirePermission('sales', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("Invalid Invoice");

$inv = $conn->query("
    SELECT si.invoice_no, si.invoice_date, si.net_total, si.received_amount, si.balance_amount,
           si.status,
           c.name AS client_name, c.phone AS client_phone,
           cm.company_name
    FROM sales_invoices si
    JOIN clients c       ON c.id  = si.client_id
    JOIN company_master cm ON cm.id = si.company_id
    WHERE si.id = $id
")->fetch_assoc();
?>

<link rel="stylesheet" href="../assets/css/screen_invoice.css">
<link rel="stylesheet" id="templateStyle">
<script src="../assets/js/JsBarcode.all.min.js"></script>
<script src="../assets/js/qrcode.min.js"></script>


<div class="page-header no-print">
    <h2><i class="fas fa-eye" style="color:var(--primary);margin-right:8px;"></i>View Invoice</h2>
    <div style="display:flex;gap:10px;align-items:center;">
        <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;color:var(--text-secondary);text-transform:none;letter-spacing:0;">
            Template:
            <select id="templateSelect" class="btn btn-secondary btn-sm" style="padding:6px 10px;font-weight:500;">
                <option value="simple">Simple</option>
                <option value="tally">Tally</option>
                <option value="modern">Modern</option>
            </select>
        </label>
        <button onclick="printA4()" class="btn btn-primary">
            <i class="fas fa-print"></i> Print A4
        </button>
        <button onclick="downloadPdf()" class="btn btn-danger no-print">
            <i class="fas fa-file-pdf"></i> PDF
        </button>
        <button onclick="printThermal()" class="btn btn-secondary">
            <i class="fas fa-receipt"></i> Thermal
        </button>
        <?php if (!empty($inv['client_phone'])): ?>
        <button onclick="sendWhatsApp()" class="btn btn-success no-print" style="background:#25d366;border-color:#25d366;">
            <i class="fab fa-whatsapp"></i> WhatsApp
        </button>
        <?php endif; ?>
        <?php if (($inv['status'] ?? '') === 'final'): ?>
        <a href="../sales_return/create.php?invoice_id=<?= $id ?>" class="btn btn-secondary no-print">
            <i class="fas fa-rotate-left"></i> Sales Return
        </a>
        <?php endif; ?>
        <a href="index.php" class="btn btn-secondary no-print">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>
</div>

<!-- Invoice Preview Area -->
<div class="panel">
    <div class="panel-body" style="padding:0;">
        <div id="invoicePreview" style="min-height:300px;padding:20px;">
            <div style="display:flex;align-items:center;justify-content:center;height:200px;color:var(--text-muted);">
                <i class="fas fa-spinner fa-spin" style="font-size:24px;margin-right:10px;"></i> Loading invoice...
            </div>
        </div>
    </div>
</div>

<script>
const invoiceId = <?= $id ?>;
const waPhone   = '<?= preg_replace('/\D/', '', $inv['client_phone'] ?? '') ?>';
const waData    = {
    clientName  : <?= json_encode($inv['client_name']    ?? '') ?>,
    companyName : <?= json_encode($inv['company_name']   ?? '') ?>,
    invoiceNo   : <?= json_encode($inv['invoice_no']     ?? '') ?>,
    date        : <?= json_encode(date('d-m-Y', strtotime($inv['invoice_date'] ?? 'now'))) ?>,
    netTotal    : <?= json_encode(number_format((float)($inv['net_total'] ?? 0), 2)) ?>,
    received    : <?= json_encode(number_format((float)($inv['received_amount'] ?? 0), 2)) ?>,
    balance     : <?= json_encode(number_format((float)($inv['balance_amount'] ?? 0), 2)) ?>
};

function loadLayout() {
    const template = document.getElementById('templateSelect').value;
    document.getElementById('templateStyle').href = `templates/${template}/style.css`;

    document.getElementById('invoicePreview').innerHTML =
        '<div style="display:flex;align-items:center;justify-content:center;height:200px;color:#94a3b8;">' +
        '<i class="fas fa-spinner fa-spin" style="font-size:20px;margin-right:10px;"></i> Loading...</div>';

    fetch(`layout_loader.php?id=${invoiceId}&template=${template}&type=invoice`)
    .then(r => r.text())
    .then(html => {
        document.getElementById('invoicePreview').innerHTML = html;
        setTimeout(renderCodes, 50);
    })
    .catch(() => {
        document.getElementById('invoicePreview').innerHTML =
            '<div style="color:var(--danger);padding:20px;"><i class="fas fa-exclamation-circle"></i> Failed to load invoice.</div>';
    });
}

function printA4() {
    const template = document.getElementById('templateSelect').value;
    window.open(`print_a4.php?id=${invoiceId}&template=${template}`, '_blank', 'width=900,height=720,scrollbars=yes');
}
function downloadPdf() {
    const template = document.getElementById('templateSelect').value;
    window.location.href = `pdf_download.php?id=${invoiceId}&template=${template}`;
}
function printThermal() {
    window.open(`layout_loader_thermal.php?id=${invoiceId}`, 'thermal_print', 'width=560,height=780,scrollbars=yes');
}

function renderCodes() {
    const barcodeEl = document.getElementById('barcode');
    if (barcodeEl) {
        JsBarcode(barcodeEl, barcodeEl.dataset.invoice, {
            format: 'CODE128', width: 1.4, height: 45, displayValue: false, margin: 0
        });
    }
    const qrEl = document.getElementById('upiQR');
    if (qrEl) {
        qrEl.innerHTML = '';
        new QRCode(qrEl, {
            text: `upi://pay?pa=${qrEl.dataset.upi}&pn=${encodeURIComponent(qrEl.dataset.name)}&am=${qrEl.dataset.amount}`,
            width: 120, height: 120
        });
    }
}

function sendWhatsApp() {
    // Normalize phone: ensure 91 country code for India
    let phone = waPhone.replace(/^0+/, '');
    if (phone.length === 10) phone = '91' + phone;

    const bal = parseFloat(waData.balance.replace(/,/g, ''));
    const msg =
        `Dear ${waData.clientName},\n\n` +
        `Your invoice from *${waData.companyName}* is ready.\n\n` +
        `📄 Invoice No : *${waData.invoiceNo}*\n` +
        `📅 Date       : ${waData.date}\n` +
        `💰 Amount     : ₹${waData.netTotal}\n` +
        `✅ Paid       : ₹${waData.received}\n` +
        (bal > 0 ? `⚠️ Balance    : ₹${waData.balance}\n` : ``) +
        `\nThank you for your business! 🙏`;

    window.open('https://wa.me/' + phone + '?text=' + encodeURIComponent(msg), '_blank');
}

document.getElementById('templateSelect').addEventListener('change', loadLayout);
loadLayout();
</script>

<?php require_once '../includes/footer.php'; ?>
