<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/includes/layout.php';
require_once dirname(__DIR__) . '/includes/report-data.php';

function crm_amount_words(float $amount): string
{
    $number = (int)round($amount);
    if ($number === 0) return 'Zero Rupees Only';
    $ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten',
        'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    $tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    $underHundred = static function (int $value) use ($ones, $tens): string {
        return $value < 20 ? $ones[$value] : trim($tens[intdiv($value, 10)] . ' ' . $ones[$value % 10]);
    };
    $underThousand = static function (int $value) use ($ones, $underHundred): string {
        return $value < 100 ? $underHundred($value) : trim($ones[intdiv($value, 100)] . ' Hundred ' . $underHundred($value % 100));
    };
    $parts = [];
    foreach ([[10000000, 'Crore'], [100000, 'Lakh'], [1000, 'Thousand']] as [$unit, $label]) {
        if ($number >= $unit) {
            $parts[] = $underThousand(intdiv($number, $unit)) . ' ' . $label;
            $number %= $unit;
        }
    }
    if ($number > 0) $parts[] = $underThousand($number);
    return trim(implode(' ', $parts)) . ' Rupees Only';
}

$db = crm_report_db();
$quoteId = max(0, (int)($_GET['id'] ?? 0));
$quote = $company = [];
$items = $terms = [];
$error = '';
try {
    if (!$db || $quoteId <= 0) throw new RuntimeException('Select a valid quotation.');
    $quote = crm_report_query(
        $db,
        "SELECT q.*,a.id lead_no,
                COALESCE(NULLIF(st.name,''),IF(q.status<>'',CONCAT('Status #',q.status),'Not assigned')) status_label,
                COALESCE(NULLIF(c.companyname,''),CONCAT('Customer #',q.custid)) company,
                COALESCE(c.address,'') address,COALESCE(c.gstno,'') customer_gst,
                COALESCE(NULLIF(ms.name,''),'') state_name,COALESCE(NULLIF(md.name,''),'') district_name,
                COALESCE(NULLIF(mt.name,''),'') taluka_name,
                COALESCE(NULLIF(c.contactperson1,''),'') contact_person,
                COALESCE(NULLIF(c.contactno1,''),NULLIF(c.contactnumber,''),NULLIF(c.officecontact,''),'') contact_no
         FROM jos_crm_quotations q
         LEFT JOIN jos_crm_leadentry a ON a.id=q.leadid
         LEFT JOIN jos_crm_mcustomers c ON c.id=q.custid
         LEFT JOIN jos_crm_mstates ms ON ms.id=c.stateid
         LEFT JOIN jos_crm_district md ON md.id=c.districtid
         LEFT JOIN jos_crm_mcitys mt ON mt.id=c.talukaid
         LEFT JOIN jos_crm_mleadstatus st ON st.id=CAST(q.status AS UNSIGNED)
         WHERE q.id={$quoteId} LIMIT 1"
    )[0] ?? [];
    if ($quote === []) throw new RuntimeException('Quotation not found.');
    $items = crm_report_query(
        $db,
        "SELECT g.*,COALESCE(NULLIF(p.name,''),CONCAT('Product #',g.propid)) product_name
         FROM jos_crm_quotation_grid g LEFT JOIN jos_crm_crmproducts p ON p.id=g.propid
         WHERE g.qutid={$quoteId} ORDER BY g.id"
    );
    $terms = crm_report_query($db, "SELECT term,description FROM jos_crm_quotation_terms WHERE qutid={$quoteId} ORDER BY id");
    if (crm_report_table($db, 'jos_crm_mcompany')) {
        $company = crm_report_query($db, 'SELECT * FROM jos_crm_mcompany ORDER BY id LIMIT 1')[0] ?? [];
    }
} catch (Throwable $exception) {
    $error = $exception->getMessage();
}

$sellerName = (string)($company['name'] ?? $company['companyname'] ?? 'Inventive Infotech');
$sellerAddress = (string)($company['address'] ?? '');
$sellerGst = (string)($company['gstno'] ?? $company['gst'] ?? '');
$logo = trim((string)($company['logo'] ?? ''));
$logoUrl = $logo === '' ? '' : (preg_match('#^https?://#i', $logo) ? $logo
    : (strpos($logo, '/') === 0 ? $logo : '/images/crm/' . rawurlencode(basename($logo))));
$location = implode(', ', array_filter([$quote['taluka_name'] ?? '', $quote['district_name'] ?? '', $quote['state_name'] ?? '']));

crm_page_start('Quotation Preview', 'operations', 'Legacy-compatible printable quotation');
?>
<?php if (isset($_GET['saved'])): ?><div class="quote-success"><i class="fa-solid fa-circle-check"></i> Quotation #<?= $quoteId ?> saved successfully.</div><?php endif; ?>
<?php if ($error !== ''): ?><div class="report-notice"><i class="fa-solid fa-circle-exclamation"></i><span><?= crm_e($error) ?></span></div><?php endif; ?>
<?php if ($quote !== []): ?>
<section class="lead-command-bar quote-preview-actions">
    <div><strong>Quotation #<?= $quoteId ?></strong><span>Lead #<?= (int)$quote['leadid'] ?> · <?= crm_e(crm_date($quote['date'])) ?></span></div>
    <div class="inline-actions">
        <a class="button secondary" href="<?= crm_e(crm_url('operations/quotations.php?lead_id=' . (int)$quote['leadid'])) ?>">Quotation List</a>
        <a class="button primary" href="<?= crm_e(crm_url('operations/quotation.php?id=' . $quoteId)) ?>"><i class="fa-solid fa-pen"></i> Edit</a>
        <button class="button secondary" onclick="window.print()" type="button"><i class="fa-solid fa-file-pdf"></i> Download PDF</button>
        <button class="button quote" onclick="window.print()" type="button"><i class="fa-solid fa-print"></i> Print</button>
    </div>
</section>
<article class="card quotation-document">
    <?php if ($logoUrl !== ''): ?><img class="quotation-watermark" src="<?= crm_e($logoUrl) ?>" alt=""><?php endif; ?>
    <header class="quotation-document-head">
        <div class="quotation-brand"><?php if ($logoUrl !== ''): ?><img src="<?= crm_e($logoUrl) ?>" alt="<?= crm_e($sellerName) ?>"><?php endif; ?><div><span><?= crm_e($sellerName) ?></span><h2>QUOTATION</h2><p><?= nl2br(crm_e($sellerAddress)) ?></p><?php if ($sellerGst !== ''): ?><p>GST: <?= crm_e($sellerGst) ?></p><?php endif; ?></div></div>
        <div><strong>#<?= $quoteId ?></strong><span><?= crm_e(crm_date($quote['date'])) ?></span><span class="badge blue"><?= crm_e((string)$quote['status_label']) ?></span></div>
    </header>
    <div class="quotation-parties">
        <div><small>QUOTATION FOR</small><h3><?= crm_e((string)$quote['company']) ?></h3><p><?= nl2br(crm_e((string)$quote['address'])) ?></p><?php if ($location !== ''): ?><p><?= crm_e($location) ?></p><?php endif; ?><?php if ($quote['customer_gst'] !== ''): ?><p><strong>GST:</strong> <?= crm_e((string)$quote['customer_gst']) ?></p><?php endif; ?></div>
        <div><small>CONTACT</small><h3><?= crm_e((string)($quote['contact_person'] ?: 'Not assigned')) ?></h3><p><?= crm_e((string)$quote['contact_no']) ?></p><p>Lead #<?= (int)$quote['leadid'] ?></p></div>
    </div>
    <section class="quotation-copy"><h3><?= crm_e((string)$quote['description']) ?></h3><p><?= nl2br(crm_e((string)$quote['descr'])) ?></p></section>
    <div class="table-wrap"><table class="data-table quotation-print-table"><thead><tr><th>#</th><th>Product / Description</th><th>HSN</th><th>Rate</th><th>Qty</th><th>Discount</th><th>GST</th><th>Amount</th></tr></thead><tbody><?php foreach ($items as $index => $item): ?><tr><td><?= $index + 1 ?></td><td><strong><?= crm_e((string)$item['product_name']) ?></strong><small><?= crm_e((string)$item['description']) ?></small></td><td><?= crm_e((string)$item['hsncode']) ?></td><td><?= crm_e(crm_money($item['rate'])) ?></td><td><?= crm_e(number_format((float)$item['qty'], 2)) ?></td><td><?= crm_e(crm_money($item['discount'])) ?></td><td><?= crm_e(number_format((float)$item['gst'], 2)) ?>%<small><?= crm_e(crm_money($item['gstamt'])) ?></small></td><td><strong><?= crm_e(crm_money($item['amt'])) ?></strong></td></tr><?php endforeach; ?></tbody></table></div>
    <div class="quotation-document-summary"><div><span>Subtotal</span><strong><?= crm_e(crm_money($quote['subtotal'])) ?></strong></div><div><span>GST</span><strong><?= crm_e(crm_money($quote['gst'])) ?></strong></div><div class="grand"><span>Total</span><strong><?= crm_e(crm_money($quote['total'])) ?></strong></div></div>
    <p class="quotation-amount-words"><strong>Amount in words:</strong> <?= crm_e(crm_amount_words((float)$quote['total'])) ?></p>
    <div class="quotation-bottom-grid">
        <section><h3>Bank Details</h3><dl class="quotation-bank"><div><dt>Account Holder</dt><dd><?= crm_e((string)($company['acholder'] ?? '-')) ?></dd></div><div><dt>Bank</dt><dd><?= crm_e((string)($company['bankname'] ?? '-')) ?></dd></div><div><dt>Account No.</dt><dd><?= crm_e((string)($company['acno'] ?? '-')) ?></dd></div><div><dt>Account Type</dt><dd><?= crm_e((string)($company['actype'] ?? '-')) ?></dd></div><div><dt>IFSC</dt><dd><?= crm_e((string)($company['ifsc'] ?? '-')) ?></dd></div></dl></section>
        <?php if ($terms !== []): ?><section class="quotation-document-terms"><h3>Terms and Conditions</h3><ol><?php foreach ($terms as $term): ?><li><strong><?= crm_e((string)$term['term']) ?></strong><span><?= crm_e((string)$term['description']) ?></span></li><?php endforeach; ?></ol></section><?php endif; ?>
    </div>
    <footer class="quotation-document-footer"><span>Thank you for your business.</span><strong>For <?= crm_e($sellerName) ?></strong></footer>
</article>
<?php endif; ?>
<?php crm_page_end(); ?>
