<?php
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'auth.php';
include "db.php";

// GET se safe integer parse karein
$purchase_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$purchase_id) {
    die("Invalid Purchase Bill ID");
}

/* 📊 1. FETCH MAIN PURCHASE & SUPPLIER DATA */
$query = "
    SELECT 
        p.id as purchase_no,
        p.purchase_date,
        p.sub_total,
        p.discount_amount,
        p.tax_amount,
        p.other_charges,
        p.round_off,
        p.grand_total,
        s.name as supplier_name
    FROM purchases p
    LEFT JOIN suppliers s ON p.supplier_id = s.id
    WHERE p.id = ?
";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $purchase_id);
$stmt->execute();
$result = $stmt->get_result();
$purchase = $result->fetch_assoc();
$stmt->close();

if (!$purchase) {
    die("Purchase Invoice Not Found inside System Databases!");
}

$sub_total = $purchase['sub_total'] ?? $purchase['grand_total'];
$tax = $purchase['tax_amount'] ?? 0;
$discount = $purchase['discount_amount'] ?? 0;
$other = $purchase['other_charges'] ?? 0;
$round_off = $purchase['round_off'] ?? 0;

/* 📦 2. FETCH INDIVIDUAL ITEM DETAILS FROM `purchase_items` */
$items_query = "
    SELECT 
        pi.price,
        pi.quantity,
        pi.total,
        p.product_name
    FROM purchase_items pi
    LEFT JOIN products p ON pi.product_id = p.product_id
    WHERE pi.purchase_id = ?
";

$stmt_items = $conn->prepare($items_query);
$stmt_items->bind_param("i", $purchase_id);
$stmt_items->execute();
$items_result = $stmt_items->get_result();
$products_list = [];
while ($item_row = $items_result->fetch_assoc()) {
    $products_list[] = $item_row;
}
$stmt_items->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Purchase Bill #<?= $purchase['purchase_no'] ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">

<style>
:root {
    --primary-color: #0d6efd; 
    --dark-color: #0C1F3A;
    --light-bg: #f8f9fa;
    --border-color: #e5e7eb;
}

body {
    background: #eef2f7;
    font-family: 'Poppins', sans-serif;
    margin: 0;
    padding: 12px;
    color: #4b5563;
}

/* 🌟 WRAPPER: ab full width hy aur scale-wrapper ko center karta hy */
.invoice-wrapper {
    width: 100%;
    margin: 10px auto;
}

/* 🌟🌟 SCALE WRAPPER
   Ye wrapper .invoice-card ke scaled (chhote) size ke barabar apni
   height/width khud set karta hy (JS se), taake neeche ke buttons
   (.actions) card ke upar overlap na hoon aur blank jagah bhi na bache */
.invoice-scale-wrapper {
    position: relative;
    margin: 0 auto;
}

/* 🌟 FIXED DESIGN WIDTH: Bill hamesha isi 850px "asal" (laptop wale)
   design par bani rehti hy — mobile par ye reflow/wrap nahi hoti,
   bas JS is poore card ko transform: scale() se chhota kar deta hy.
   Isi wajah se mobile par bhi bilkul professional/laptop jaisa layout
   dikhta hy, sirf size chhota — bilkul Sales Invoice jesa. */
.invoice-card {
    width: 850px;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.04);
    padding: 25px 35px;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    transform-origin: top left;
}
.invoice-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(90deg, var(--primary-color), #0a58ca);
}

.invoice-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    border-bottom: 2px solid var(--light-bg);
    padding-bottom: 15px;
    margin-bottom: 15px;
}
.company-details h1 {
    margin: 0;
    font-size: 24px;
    color: var(--dark-color);
    font-weight: 700;
}
.company-details p {
    margin: 2px 0;
    font-size: 12px;
    color: #6b7280;
}
.invoice-status-box {
    text-align: right;
}
.invoice-status-box h2 {
    margin: 0;
    font-size: 22px;
    color: var(--primary-color);
    font-weight: 700;
}

.status-dropdown {
    padding: 6px 12px;
    border-radius: 30px;
    font-size: 11px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    outline: none;
    display: inline-block;
    margin-top: 5px;
    font-family: inherit;
    text-align: center;
    transition: 0.2s;
}
.status-received { background-color: rgba(40, 167, 69, 0.1); color: #28a745; }
.status-pending { background-color: rgba(220, 53, 69, 0.1); color: #dc3545; }
.status-partial { background-color: rgba(255, 152, 0, 0.1); color: #ff9800; }

.invoice-details-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    margin-bottom: 15px;
}
.info-block h4 {
    margin: 0 0 4px 0;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #9ca3af;
}
.info-block p {
    margin: 1px 0;
    font-size: 13px;
}
.info-block .client-name {
    font-size: 15px;
    font-weight: 600;
    color: var(--dark-color);
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 15px;
}
thead tr {
    background-color: var(--light-bg);
    border-top: 1px solid var(--border-color);
    border-bottom: 1px solid var(--border-color);
}
th {
    padding: 10px;
    font-size: 12px;
    font-weight: 600;
    color: var(--dark-color);
    text-align: left;
}
td {
    padding: 10px;
    border-bottom: 1px solid #f3f4f6;
    font-size: 13px;
    color: #4b5563;
}
.text-right {
    text-align: right;
}

.invoice-summary {
    display: flex;
    justify-content: flex-end;
    margin-top: 5px;
}
.summary-table {
    width: 280px;
    margin-bottom: 0;
}
.summary-table tr td {
    padding: 4px 0;
    border-bottom: none;
    font-size: 13px;
}
.summary-table tr.total-row td {
    border-top: 2px solid var(--border-color);
    font-size: 16px;
    font-weight: 700;
    color: var(--dark-color);
    padding-top: 8px;
}

.narration-container {
    margin-top: 15px;
    padding-top: 10px;
    border-top: 1px dashed var(--border-color);
}
.narration-container h5 {
    margin: 0 0 4px 0;
    font-size: 12px;
    color: var(--dark-color);
    font-weight: 600;
}
.narration-textarea {
    width: 100%;
    height: 45px;
    padding: 6px 10px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-family: inherit;
    font-size: 12px;
    color: #333;
    box-sizing: border-box;
    resize: none;
    background: #fafafa;
}

.invoice-footer {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    border-top: 1px solid var(--light-bg);
    padding-top: 15px;
}
.terms {
    max-width: 60%;
}
.terms h5 {
    margin: 0 0 4px 0;
    font-size: 12px;
    color: var(--dark-color);
}
.terms p {
    margin: 0;
    font-size: 11px;
    color: #9ca3af;
    line-height: 1.4;
}
.signature-block {
    text-align: center;
    width: 150px;
}
.signature-line {
    border-bottom: 1px solid #9ca3af;
    margin-bottom: 4px;
    height: 30px;
}
.signature-block p {
    margin: 0;
    font-size: 11px;
}

/* Actions Section — ye scaled card ke bahar, normal size me hi rehte hain */
.actions {
    max-width: 850px;
    margin: 20px auto 0 auto;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
    padding: 0 10px;
    box-sizing: border-box;
}
.right-actions {
    display: flex;
    gap: 10px;
}
.btn {
    padding: 10px 18px;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    border: none;
    transition: 0.3s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    white-space: nowrap;
}
.btn-print {
    background: var(--dark-color);
    color: #fff;
}
.btn-back {
    background: #e5e7eb;
    color: #374151;
}
.btn-share {
    background: #007bff;
    color: #fff;
}
.btn-share:hover {
    background: #0056b3;
}
.btn-share:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

/* 🌟 SHARE FORMAT CHOICE MODAL (Image vs PDF) */
.share-modal-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(12, 31, 58, 0.55);
    z-index: 999;
    align-items: center;
    justify-content: center;
    padding: 20px;
}
.share-modal-box {
    background: #fff;
    border-radius: 14px;
    padding: 25px;
    width: 100%;
    max-width: 320px;
    text-align: center;
    box-shadow: 0 15px 40px rgba(0,0,0,0.2);
}
.share-modal-box h3 {
    margin: 0 0 18px 0;
    font-size: 15px;
    color: var(--dark-color);
    font-weight: 600;
}
.share-modal-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.btn-modal-image, .btn-modal-pdf {
    width: 100%;
    padding: 12px;
    border-radius: 10px;
    border: none;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: 0.2s;
}
.btn-modal-image {
    background: rgba(13, 110, 253, 0.1);
    color: var(--primary-color);
}
.btn-modal-image:hover { background: rgba(13, 110, 253, 0.2); }
.btn-modal-pdf {
    background: rgba(12, 31, 58, 0.08);
    color: var(--dark-color);
}
.btn-modal-pdf:hover { background: rgba(12, 31, 58, 0.16); }
.share-modal-cancel {
    margin-top: 14px;
    background: none;
    border: none;
    color: #9ca3af;
    font-size: 12px;
    cursor: pointer;
    text-decoration: underline;
}

/* 🌟🌟 SIRF IMAGE (PNG) EXPORT KE LIYE BARA FONT
   Ye class sirf us waqt lagti hai jab "Image" share ki ja rahi ho
   (offscreen clone par) — taake Image me text bara aur asani se
   parha jaye. Live page ya PDF par is ka koi asar nahi hota, wo
   bilkul pehle jaise hi rahenge. */
.invoice-card.capture-large-text h1 { font-size: 30px; }
.invoice-card.capture-large-text .company-details p { font-size: 15px; }
.invoice-card.capture-large-text .invoice-status-box h2 { font-size: 27px; }
.invoice-card.capture-large-text .invoice-status-box p { font-size: 15px; }
.invoice-card.capture-large-text .status-dropdown,
.invoice-card.capture-large-text .status-received,
.invoice-card.capture-large-text .status-pending,
.invoice-card.capture-large-text .status-partial { font-size: 14px; padding: 8px 16px; }
.invoice-card.capture-large-text .info-block h4 { font-size: 13px; }
.invoice-card.capture-large-text .info-block p { font-size: 15px; }
.invoice-card.capture-large-text .info-block .client-name { font-size: 19px; }
.invoice-card.capture-large-text th { font-size: 15px; padding: 12px; }
.invoice-card.capture-large-text td { font-size: 15px; padding: 12px; }
.invoice-card.capture-large-text .summary-table { width: 320px; }
.invoice-card.capture-large-text .summary-table tr td { font-size: 15px; padding: 6px 0; }
.invoice-card.capture-large-text .summary-table tr.total-row td { font-size: 20px; }
.invoice-card.capture-large-text .narration-container h5 { font-size: 15px; }
.invoice-card.capture-large-text .narration-textarea,
.invoice-card.capture-large-text .narration-container div { font-size: 14px; }
.invoice-card.capture-large-text .terms h5 { font-size: 14px; }
.invoice-card.capture-large-text .terms p { font-size: 13.5px; }
.invoice-card.capture-large-text .signature-block p { font-size: 13px; }

/* PRINT PREVIEW RULES — print hamesha asal (unscaled) 850px design use kare */
@media print {
    body { background: #fff; padding: 0; }
    .invoice-scale-wrapper { height: auto !important; width: auto !important; }
    .invoice-card {
        transform: none !important;
        box-shadow: none; padding: 0; margin: 0;
    }
    .actions { display: none !important; }
    .status-dropdown {
        border: none !important;
        appearance: none;
        -webkit-appearance: none;
        background: transparent !important;
        padding: 0 !important;
        font-size: 12px;
        font-weight: 700;
    }
    .narration-textarea {
        border: none !important;
        background: transparent !important;
        padding: 0 !important;
        height: auto !important;
    }
}
</style>
</head>
<body>

<div class="invoice-wrapper">
    <!-- 🌟🌟 SCALE WRAPPER: JS is ki height/width set karega taake scaled card
         ke around koi extra khali jagah ya overlap na ho -->
    <div class="invoice-scale-wrapper" id="invoiceScaleWrapper">
        <div class="invoice-card" id="invoiceCard">

            <div class="invoice-header">
                <div class="company-details">
                    <h1>TAMEER AL MADINA</h1>
                    <p>📍 BARKA INDUSTRIAL AREA</p>
                    <p>📞 +968 97300223 | +968 98300224 | tameeralmadinatrading@gmail.com</p>
                </div>
                <div class="invoice-status-box">
                    <h2>PURCHASE BILL</h2>
                    <p style="margin:0; font-size:13px; color:#6b7280;"># PCH-00<?= $purchase['purchase_no'] ?></p>
                    
                    <select id="deliveryStatusSelect" class="status-dropdown status-received" onchange="updateStatusColor(this)">
                        <option value="received" class="status-received">Stock Received</option>
                        <option value="pending" class="status-pending">Stock Pending</option>
                        <option value="partial" class="status-partial">50% Done / 50% Pending</option>
                    </select>
                </div>
            </div>

            <div class="invoice-details-grid">
                <div class="info-block">
                    <h4>Vendor / Supplier:</h4>
                    <p class="client-name"><?= htmlspecialchars($purchase['supplier_name'] ?? 'Unknown Supplier') ?></p>
                </div>
                <div class="info-block" style="text-align: right;">
                    <h4>Details:</h4>
                    <p><strong>Date Received:</strong> <?= date('d M Y', strtotime($purchase['purchase_date'])) ?></p>
                </div>
            </div>

            <table>
                <thead>
                    <tr>
                        <th style="width: 8%;">Sr.</th>
                        <th style="width: 47%;">Product Name</th>
                        <th style="width: 15%; text-align: right;">Cost Price</th>
                        <th style="width: 10%; text-align: right;">Qty</th>
                        <th style="width: 20%; text-align: right;">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $sr = 1;
                    if(count($products_list) > 0) {
                        foreach($products_list as $item) {
                            echo "<tr>
                                <td>{$sr}</td>
                                <td><strong>" . htmlspecialchars($item['product_name'] ?? 'Item Details') . "</strong></td>
                                <td class='text-right'>" . number_format($item['price'], 2) . "</td>
                                <td class='text-right'>" . number_format($item['quantity'], 0) . "</td>
                                <td class='text-right'>" . number_format($item['total'], 2) . " PKR</td>
                            </tr>";
                            $sr++;
                        }
                    } else {
                        echo "<tr>
                            <td colspan='5' style='text-align:center;'>No itemized data records found</td>
                        </tr>";
                    }
                    ?>
                </tbody>
            </table>

            <div class="invoice-summary">
                <table class="summary-table">
                    <tr>
                        <td>Sub Total:</td>
                        <td class="text-right"><?= number_format($sub_total, 2) ?> PKR</td>
                    </tr>
                    <?php if($tax > 0): ?>
                    <tr>
                        <td>(+) Tax:</td>
                        <td class="text-right" style="color: #d9534f;"><?= number_format($tax, 2) ?> PKR</td>
                    </tr>
                    <?php endif; ?>
                    <?php if($discount > 0): ?>
                    <tr>
                        <td>(-) Discount Received:</td>
                        <td class="text-right" style="color: #28a745;"><?= number_format($discount, 2) ?> PKR</td>
                    </tr>
                    <?php endif; ?>
                    <?php if($other > 0): ?>
                    <tr>
                        <td>(+) Other Charges:</td>
                        <td class="text-right"><?= number_format($other, 2) ?> PKR</td>
                    </tr>
                    <?php endif; ?>
                    <?php if($round_off != 0): ?>
                    <tr>
                        <td>(+/-) Round Off:</td>
                        <td class="text-right"><?= number_format($round_off, 2) ?> PKR</td>
                    </tr>
                    <?php endif; ?>
                    <tr class="total-row">
                        <td>Grand Total:</td>
                        <td class="text-right"><?= number_format($purchase['grand_total'], 2) ?> PKR</td>
                    </tr>
                </table>
            </div>

            <div class="narration-container">
                <h5>Purchase Notes / Delivery Remarks:</h5>
                <textarea class="narration-textarea" placeholder="Custom narration..."></textarea>
            </div>

            <div class="invoice-footer">
                <div class="terms">
                    <h5>Auditing Info</h5>
                    <p>1. Stock is safely updated inside the primary inventory database.<br>
                       2. This is an official auto-calculated computer statement bill.</p>
                </div>
                <div class="signature-block">
                    <div class="signature-line"></div>
                    <p>Store Manager</p>
                </div>
            </div>

        </div>
    </div>

    <div class="actions">
        <a href="purchase_list.php" class="btn btn-back">Back to Purchase List</a>
        <div class="right-actions">
            <button onclick="shareBill()" id="shareBtn" class="btn btn-share">Share Bill</button>
            <button onclick="window.print()" class="btn btn-print">Print Bill</button>
        </div>
    </div>

</div>

<!-- 🌟 SHARE FORMAT CHOICE MODAL (Image ya PDF) -->
<div class="share-modal-overlay" id="shareModalOverlay">
    <div class="share-modal-box">
        <h3>Bill kis format me share karni hai?</h3>
        <div class="share-modal-actions">
            <button class="btn-modal-image" onclick="generateAndShare('image')">🖼️ Image (PNG)</button>
            <button class="btn-modal-pdf" onclick="generateAndShare('pdf')">📄 PDF</button>
        </div>
        <button class="share-modal-cancel" onclick="closeShareModal()">Cancel</button>
    </div>
</div>

<!-- 🌟 Libraries used to capture the bill as an image / PDF before sharing -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

<script>
    /* 🌟🌟 MOBILE PAR "LAPTOP JAISA" PROFESSIONAL LAYOUT
       Bill hamesha 850px ke fixed "asal" design par bani rehti hy (koi
       reflow/wrap nahi). Ye function sirf poore card ko CSS transform: scale()
       se itna chhota kar deta hy ke pura card kisi bhi mobile screen me
       (bina kisi cut/wrap ke) fit ho jaye — bilkul waisa hi jaisa laptop par
       dikhta hy, sirf size choti. Scale-wrapper ki height/width bhi update
       hoti hy taake neeche buttons theek jagah par rahein aur koi khali
       jagah ya overlap na ho. */
    function scaleInvoiceForScreen() {
        const card = document.getElementById('invoiceCard');
        const scaleWrapper = document.getElementById('invoiceScaleWrapper');
        const BASE_WIDTH = 850; // wahi fixed design width jo laptop par use hoti hy

        let availableWidth = window.innerWidth - 20;
        let scale = Math.min(1, availableWidth / BASE_WIDTH); // kabhi 1 se zyada zoom nahi karna

        card.style.transform = `scale(${scale})`;

        let naturalHeight = card.offsetHeight;

        scaleWrapper.style.width = (BASE_WIDTH * scale) + 'px';
        scaleWrapper.style.height = (naturalHeight * scale) + 'px';
        scaleWrapper.style.margin = '0 auto';
    }

    window.addEventListener('load', scaleInvoiceForScreen);
    window.addEventListener('resize', scaleInvoiceForScreen);
    window.addEventListener('orientationchange', scaleInvoiceForScreen);

    function updateStatusColor(selectElement) {
        selectElement.className = "status-dropdown";
        if(selectElement.value === "received") selectElement.classList.add("status-received");
        if(selectElement.value === "pending") selectElement.classList.add("status-pending");
        if(selectElement.value === "partial") selectElement.classList.add("status-partial");
    }

    /* 🌟 SHARE BUTTON: Sirf format-choice modal open karta hai (Image ya PDF) */
    function shareBill() {
        document.getElementById('shareModalOverlay').style.display = 'flex';
    }

    function closeShareModal() {
        document.getElementById('shareModalOverlay').style.display = 'none';
    }

    /* 🌟🌟 MOBILE PAR BILL CUT/CROP HONE KA MASLA + NON-EDITABLE EXPORT
       Mobile screen chhoti hoti hai, is liye live invoice-card element ab
       CSS transform: scale() se visually chhota dikhta hy — is liye capture
       se pehle ye function transform ko hata (reset) kar ke ek fixed
       850px width wala INVISIBLE (offscreen) CLONE banata hy, taake
       image/PDF hamesha FULL SIZE aur SHARP (blurry nahi) bane.

       Isi tarah <select> dropdown aur <textarea> jaise real form elements
       html2canvas theek se render nahi kar pata — aur ye asal form elements
       hone ki wajah se export dikhne me bhi "editable box" jaisa lagta tha.
       Isliye inhe plain, flat (ghair-editable) text/div se replace kar diya
       jata hy — supplier sirf dekh sakega, edit nahi kar sakega. */
    function prepareCaptureClone(sourceElement, format) {
        let clone = sourceElement.cloneNode(true);

        // Sirf Image (PNG) ke liye bara/readable font wali class lagayein — PDF par asar nahi
        if (format === 'image') {
            clone.classList.add('capture-large-text');

            // "# PCH-00xx" line par pehle se inline font-size laga hua hy (jo CSS class se
            // override nahi hota), is liye ise seedha bara karte hain taake achi tarah visible ho
            let pchNoEl = clone.querySelector('.invoice-status-box p');
            if (pchNoEl) {
                pchNoEl.style.fontSize = '17px';
                pchNoEl.style.fontWeight = '600';
                pchNoEl.style.color = '#374151';
            }
        }

        // Delivery status <select> ko plain, flat (ghair-clickable) text badge se replace karein
        let originalSelect = sourceElement.querySelector('#deliveryStatusSelect');
        let cloneSelect = clone.querySelector('#deliveryStatusSelect');
        if (originalSelect && cloneSelect) {
            let selectedOption = originalSelect.options[originalSelect.selectedIndex];
            let statusDiv = document.createElement('div');
            statusDiv.className = cloneSelect.className; // status-received / status-pending / status-partial classes
            statusDiv.style.cssText = "padding:6px 12px;border-radius:30px;font-size:11px;font-weight:600;display:inline-block;margin-top:5px;text-align:center;font-family:inherit;";
            statusDiv.innerText = selectedOption ? selectedOption.text : '';
            cloneSelect.parentNode.replaceChild(statusDiv, cloneSelect);
        }

        // Purchase Notes <textarea> ko plain, flat (ghair-editable) text box se replace karein
        let originalTextarea = sourceElement.querySelector('.narration-textarea');
        let cloneTextarea = clone.querySelector('.narration-textarea');
        if (originalTextarea && cloneTextarea) {
            let textDiv = document.createElement('div');
            textDiv.style.cssText = "width:100%;min-height:45px;padding:6px 10px;border:1px solid #e5e7eb;border-radius:6px;font-family:inherit;font-size:12px;color:#333;background:#fafafa;white-space:pre-wrap;box-sizing:border-box;";
            textDiv.innerText = originalTextarea.value || '';
            cloneTextarea.parentNode.replaceChild(textDiv, cloneTextarea);
        }

        // Clone ko screen se bahar, lekin FIXED desktop width (850px) aur
        // BILKUL UNSCALED (transform: none) rakhein, taake mobile ho ya
        // desktop, bill hamesha poori, sharp aur full-size capture ho
        clone.style.transform = "none";
        clone.style.width = "850px";
        clone.style.maxWidth = "850px";
        clone.style.boxSizing = "border-box";

        let container = document.createElement('div');
        container.style.cssText = "position:fixed;top:0;left:-99999px;width:850px;background:#fff;z-index:-1;";
        container.appendChild(clone);
        document.body.appendChild(container);

        return { clone: clone, container: container };
    }

    /* 🌟 A4 CANVAS BANANE WALA HELPER (SIRF PDF KE LIYE)
       Bill ke screenshot ko ek proper A4-size canvas (white background,
       margins ke sath, center me) par professional tareeqe se fit karta hai */
    function buildA4Canvas(sourceCanvas) {
        // A4 ratio 210mm x 297mm ~ 150 DPI par
        const A4_WIDTH = 1240;
        const A4_HEIGHT = 1754;
        const MARGIN = 50;

        let a4Canvas = document.createElement('canvas');
        a4Canvas.width = A4_WIDTH;
        a4Canvas.height = A4_HEIGHT;
        let ctx = a4Canvas.getContext('2d');

        // White background (professional look)
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, A4_WIDTH, A4_HEIGHT);

        let availableWidth = A4_WIDTH - (MARGIN * 2);
        let availableHeight = A4_HEIGHT - (MARGIN * 2);

        // Bill ko available space ke andar proportionally fit karein
        let scale = Math.min(availableWidth / sourceCanvas.width, availableHeight / sourceCanvas.height);
        let drawWidth = sourceCanvas.width * scale;
        let drawHeight = sourceCanvas.height * scale;

        // Center karein
        let offsetX = (A4_WIDTH - drawWidth) / 2;
        let offsetY = MARGIN;

        ctx.drawImage(sourceCanvas, offsetX, offsetY, drawWidth, drawHeight);

        return a4Canvas;
    }

    /* 🌟🌟 IMAGE (PNG) KO PORTRAIT SHAPE DENE WALA HELPER (SIRF IMAGE KE LIYE)
       PDF bilkul pehle jesi hi rahegi (koi tabdeeli nahi).
       Image ab bhi A4 ki tarah PORTRAIT (khari) shape ki banti hy — lekin
       PDF ki tarah bill ko chhota kar ke poore page me "fit" nahi kiya
       jata. Bill apne asal, bare/readable size (jo pehle se hi 2x sharp
       hy) par hi rehti hy — bas agar wo A4 jitni lambi (portrait) nahi hy,
       to sirf neeche halka safed space add ho jata hy taake overall shape
       khari (portrait) ban jaye. Upar bhi thora zyada white space chhoda
       jata hy taake dikhne me acha lage. */
    function buildPortraitImageCanvas(sourceCanvas, sidePadding, topPadding) {
        const A4_RATIO = 210 / 297; // sirf SHAPE ke liye — content ko shrink nahi karta

        let contentWidth = sourceCanvas.width + (sidePadding * 2);
        let contentHeight = sourceCanvas.height + topPadding + sidePadding; // upar zyada, neeche/sides kam

        let canvasWidth = contentWidth;
        // Height ko itna rakhein ke A4-portrait ratio pura ho, warna asal content height hi rakhein
        let canvasHeight = Math.max(contentHeight, canvasWidth / A4_RATIO);

        let canvas = document.createElement('canvas');
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        let ctx = canvas.getContext('2d');

        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);
        ctx.drawImage(sourceCanvas, sidePadding, topPadding);

        return canvas;
    }

    /* 🌟 MAIN FUNCTION: Bill ko user ki choice ke mutabiq Image (PNG, portrait,
       bara/readable text) ya A4-size PDF me generate karke WhatsApp par
       share karta hai (koi extra text ke bagair, sirf file — file hamesha
       flat/ghair-editable image hoti hai) */
    function generateAndShare(format) {
        closeShareModal();

        let shareBtn = document.getElementById('shareBtn');
        let originalInvoiceElement = document.getElementById('invoiceCard');
        let pchNo = "<?= $purchase['purchase_no'] ?>";

        shareBtn.disabled = true;
        shareBtn.innerText = "Generating...";

        // Mobile par bhi FULL, sharp aur flat (non-editable) capture ke liye fixed-width clone taiyar karein
        let captureSetup = prepareCaptureClone(originalInvoiceElement, format);
        let invoiceElement = captureSetup.clone;

        html2canvas(invoiceElement, {
            scale: 2,
            useCORS: true,
            backgroundColor: "#ffffff",
            width: invoiceElement.scrollWidth,
            windowWidth: invoiceElement.scrollWidth
        }).then(function(rawCanvas) {

            // Offscreen clone ab zaroorat nahi, hata dein
            if (document.body.contains(captureSetup.container)) {
                document.body.removeChild(captureSetup.container);
            }

            if (format === 'pdf') {
                // 📄 PDF: pehle jesay hi — A4 page ke andar properly fit (koi tabdeeli nahi)
                let a4Canvas = buildA4Canvas(rawCanvas);
                const { jsPDF } = window.jspdf;
                let imgData = a4Canvas.toDataURL('image/jpeg', 0.95);
                let pdf = new jsPDF({
                    orientation: 'portrait',
                    unit: 'mm',
                    format: 'a4'
                });
                pdf.addImage(imgData, 'JPEG', 0, 0, 210, 297);
                let pdfBlob = pdf.output('blob');

                let fileName = `PurchaseBill_PCH-00${pchNo}.pdf`;
                finalizeShare(pdfBlob, fileName, 'application/pdf', shareBtn);

            } else {
                // 🖼️ Image (PNG): portrait shape, bara/readable text, A4 me fit NAHI karte
                let paddedCanvas = buildPortraitImageCanvas(rawCanvas, 40, 110);
                paddedCanvas.toBlob(function(blob) {
                    if (!blob) {
                        shareBtn.disabled = false;
                        shareBtn.innerText = "Share Bill";
                        alert("Image generate nahi ho saki. Dobara koshish karein.");
                        return;
                    }
                    let fileName = `PurchaseBill_PCH-00${pchNo}.png`;
                    finalizeShare(blob, fileName, 'image/png', shareBtn);
                }, 'image/png');
            }

        }).catch(function(error) {
            if (document.body.contains(captureSetup.container)) {
                document.body.removeChild(captureSetup.container);
            }
            shareBtn.disabled = false;
            shareBtn.innerText = "Share Bill";
            console.error("html2canvas error:", error);
            alert("Bill generate karne me masla hua. Dobara koshish karein.");
        });
    }

    /* 🌟 COMMON HELPER: Sirf FILE (bina kisi text ke) WhatsApp par share/download karta hai */
    async function finalizeShare(blob, fileName, mimeType, shareBtn) {
        let file = new File([blob], fileName, { type: mimeType });
        let shared = false;

        // Option 1: Native Share — SIRF file jayegi, koi text nahi
        if (navigator.canShare && navigator.canShare({ files: [file] })) {
            try {
                await navigator.share({ files: [file] });
                shared = true;
            } catch (err) {
                console.log("Native share cancelled/failed, falling back to download:", err);
            }
        }

        shareBtn.disabled = false;
        shareBtn.innerText = "Share Bill";

        if (shared) return;

        // Option 2: Fallback — file download karwayein aur WhatsApp chat khol dein (bina text ke)
        let downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = fileName;
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);

        let phoneNum = prompt("File download ho gayi hy.\nWhatsApp chat kholne ke liye supplier ka number darj karein (country code ke sath, e.g. 923000000000):");
        if (phoneNum) {
            let whatsappUrl = `https://api.whatsapp.com/send?phone=${phoneNum}`;
            window.open(whatsappUrl, '_blank');
            alert("WhatsApp chat khul gayi hy. Ab downloaded file (" + fileName + ") ko attach (📎) icon se manually select kar ke bhej dein.");
        }
    }
</script>

</body>
</html>