<?php
ob_start();
include 'db.php';
require 'vendor/autoload.php';

use Dompdf\Dompdf;
use Dompdf\Options;

$id = intval($_GET['id'] ?? 0);

/* ================= FETCH STOCK ================= */
$res = mysqli_query($con, "SELECT * FROM jewellery_stock WHERE id='$id'");
$invoice = mysqli_fetch_assoc($res);

if (!$invoice) {
    die("Stock Invoice not found");
}

/* ================= BASIC VALUES ================= */
$subtotal = (float)$invoice['total_value'];
$state = strtolower(trim($invoice['supplier_state']));

/* ================= STATE CODE ================= */
$state_codes = [
'andhra pradesh'=>'37','arunachal pradesh'=>'12','assam'=>'18','bihar'=>'10',
'chhattisgarh'=>'22','goa'=>'30','gujarat'=>'24','haryana'=>'06',
'himachal pradesh'=>'02','jharkhand'=>'20','karnataka'=>'29','kerala'=>'32',
'madhya pradesh'=>'23','maharashtra'=>'27','manipur'=>'14','meghalaya'=>'17',
'mizoram'=>'15','nagaland'=>'13','odisha'=>'21','punjab'=>'03',
'rajasthan'=>'08','sikkim'=>'11','tamil nadu'=>'33','telangana'=>'36',
'tripura'=>'16','uttar pradesh'=>'09','uttarakhand'=>'05',
'west bengal'=>'19','delhi'=>'07'
];

$state_code = $state_codes[$state] ?? '';

/* ================= GST ================= */
$cgst=$sgst=$igst=0;

if ($state == 'west bengal') {
    $cgst = round($subtotal * 0.015,2);
    $sgst = round($subtotal * 0.015,2);
} else {
    $igst = round($subtotal * 0.03,2);
}

/* ================= HM GST ================= */
$hm_cgst=$hm_sgst=$hm_igst=0;

if ($state == 'west bengal') {
    $hm_cgst = round($subtotal * 0.09,2);
    $hm_sgst = round($subtotal * 0.09,2);
} else {
    $hm_igst = round($subtotal * 0.18,2);
}

/* ================= FINAL ================= */
$final = $subtotal + $cgst + $sgst + $igst + $hm_cgst + $hm_sgst + $hm_igst;
$grand_total = round($final);
$round_off = $grand_total - $final;

/* ================= NUMBER TO WORDS ================= */
function numberToWords($num){
$num=round($num);
$ones=[0=>'',1=>'One',2=>'Two',3=>'Three',4=>'Four',5=>'Five',6=>'Six',7=>'Seven',8=>'Eight',9=>'Nine',10=>'Ten',11=>'Eleven',12=>'Twelve',13=>'Thirteen',14=>'Fourteen',15=>'Fifteen',16=>'Sixteen',17=>'Seventeen',18=>'Eighteen',19=>'Nineteen'];
$tens=[2=>'Twenty',3=>'Thirty',4=>'Forty',5=>'Fifty',6=>'Sixty',7=>'Seventy',8=>'Eighty',9=>'Ninety'];
if($num==0) return 'Zero';
$result='';
if($num>=100000){ $result.=numberToWords(floor($num/100000)).' Lakh '; $num%=100000; }
if($num>=1000){ $result.=numberToWords(floor($num/1000)).' Thousand '; $num%=1000; }
if($num>=100){ $result.=$ones[floor($num/100)].' Hundred '; $num%=100; }
if($num>0){
 if($num<20){ $result.=$ones[$num]; }
 else{
  $result.=$tens[floor($num/10)];
  if($num%10>0) $result.=' '.$ones[$num%10];
 }
}
return trim($result);
}
/* ================= PDF DOWNLOAD ================= */
if (isset($_GET['download'])) {

    ob_end_clean();

    $options = new Options();
    $options->set('defaultFont', 'DejaVu Sans');
    $options->set('isRemoteEnabled', true);

    $dompdf = new Dompdf($options);

    ob_start();
    include 'stock_invoice-download.php'; 
    $html = ob_get_clean();

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    $filename = "stock_invoice_{$invoice['invoice_no']}.pdf";

    header("Content-Type: application/pdf");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Cache-Control: private, max-age=0, must-revalidate");
    header("Pragma: public");

    echo $dompdf->output();
    exit;
}
/* ================= SUPPLIER ================= */
/* ================= SUPPLIER ================= */
$supplier = $invoice['purchased_from'] ?? '';
$supplier_phone = $invoice['supplier_phone'] ?? '';
$supplier_pan = $invoice['supplier_pan'] ?? '';
$supplier_gst = $invoice['supplier_gst'] ?? '';
$supplier_address = $invoice['supplier_address'] ?? '';
$supplier_city = $invoice['supplier_city'] ?? '';
$supplier_state = $invoice['supplier_state'] ?? '';
$supplier_pin = $invoice['supplier_pincode'] ?? '';
$added_date = date('d-m-Y', strtotime($invoice['added_on']));
$formatted_time = date('h:i:s A', strtotime($invoice['added_on']));
/* ================= PAYMENTS ================= */
$payments = [
    'UPI' => (float)$invoice['pay_upi'],
    'Cheque' => (float)$invoice['pay_cheque'],
    'Metal' => (float)$invoice['pay_metal'],
    'Cash' => (float)$invoice['pay_cash'],
    'Card' => (float)$invoice['pay_card']
];
 
$title = "Invoice View";
include 'include/header.php';
?>
<div id="page-wrapper">
    <div id="page-inner">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

        <style>
        body {
            font-family: 'DejaVu Sans';
            background: #f2f2f2;
            margin: 0;
            font-size: 9px;
            font-weight: 400;
        }

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
            font-weight: 900;
        }

        strong,
        b {
            font-weight: 900;
        }

        .header h2 {
            font-weight: 900;
        }

        .info-box h5 {
            font-weight: 800;
        }

        .table-invoice th {
            font-weight: 800;
        }

        .table-invoice {
            font-size: 9px;
        }

        .table-invoice th,
        .table-invoice td {
            padding: 3px 4px;
            /* 6px → 3px */
        }

        .table-invoice td {
            font-weight: 600;
        }

        .footer-note {
            font-weight: 700;
            font-size: 12px;
        }

        .invoice-box {
            max-width: 900px;
            margin: auto;
            padding: 6px 12px;
            background: #fffdf8;
            border: 3px solid #d4af37;
            color: #333;
            font-size: 10px;
        }

        .header {
            display: flex;
            align-items: center;
            gap: 20px;
            padding: 18px 0 16px;
            margin-bottom: 15px;

            border-bottom: 5px solid #d4af37;
            position: relative;
        }

        .logo img {
            width: 100px;
            height: auto;
        }

        .header-text {
            flex: 1;
            text-align: center;
        }

        .header-text h2 {
            font-size: 18px;
            /* 24px → 18px */
            letter-spacing: 2px;
        }

        .header {
            padding: 10px 0;
            margin-bottom: 8px;
        }


        .header-text p {
            margin: 2px 0;
            font-size: 12px;
            color: #7b1e1e;
        }

        .info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-top: 10px;
            font-size: 12px;
        }

        .info-box {
            border: 1px solid #e5c87a;
            padding: 6px;
            background: #fffaf0;
        }

        .info-box h5 {
            margin: 0;
            color: #8b0000;
            font-size: 12px;
            border-bottom: 1px solid #e5c87a;
        }

        .items-wrapper {
            border: 1px solid #d4af37;
            background: #fffdf8;
            display: flex;
            flex-direction: column;
            margin-top: 15px;
        }

        .items-scroll {
            flex: 1;
            overflow-y: auto;
        }

        .table-invoice {
            width: 100%;
            border-collapse: collapse;
            font-size: 9px;
        }

        .table-invoice th {
            background: #f3e2a9;
            border: 1px solid #d4af37;
            padding: 6px;
            color: #5a2a27;
        }

        .table-invoice td {
            border: 1px solid #d4af37;
            padding: 5px 6px;
            text-align: center;
        }

        .total-table {
            margin-top: auto;
        }

        .total-table td {
            background: #fff1c1;
            font-weight: bold;
            border-top: 2px solid #d4af37;
        }

        .bottom-summary {
            margin-top: 8px;
            display: flex;
            justify-content: space-between;
            font-size: 11px;
        }

        .left-box,
        .right-box {
            border: 1px dashed #888;
            background: #fffdf8;
            padding: 6px;
            margin: 5px;
        }

        .left-box .row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 6px;
        }

        .left-box .row strong {
            width: 60px;
            color: #7b1e1e;
        }

        .total-words {
            border: 1px dashed #888;
            padding: 6px 10px;
            margin-top: 10px;
            font-style: italic;
            background: #fffaf0;
        }

        .right-box table {
            width: 100%;
            border-collapse: collapse;
        }

        .right-box table tr {
            border-bottom: 1px dashed #888;
        }

        .right-box table td {
            padding: 5px 6px;
        }

        .right-box table td:first-child {
            font-weight: 600;
            color: #7b1e1e;
        }

        .right-box table td:last-child {
            text-align: right;
        }

        .footer-note {
            margin-top: 25px;
            font-style: italic;
            font-weight: bold;
            color: #a94442;
            text-align: center;
            background: #fff1c1;
            padding: 10px;
            font-size: 12px;
        }

        .footer-note a {
            color: #a94442;
            text-decoration: none;
            margin: 0 10px;
        }

        .footer-note .social-icons {
            margin-top: 10px;
        }

        .footer-note .social-icons a {
            margin-right: 15px;
            font-size: 16px;
        }

        .footer-note p {
            margin: 5px 0;
        }

        .sign-area {
            display: flex;
            justify-content: space-between;
            margin-top: 25px;
        }

        .sign-box {
            text-align: center;
            color: #7b1e1e;
        }

        @media print {
            body {
                background: #fff;
            }

            .invoice-box {
                border: none;
                padding: 0;
            }
        }

        .right-box table {
            font-size: 10px;
            /* Adjust this value as needed */
        }
        </style>
        <?php
$logoPath = __DIR__ . '/logo.png';
$logoData = base64_encode(file_get_contents($logoPath));
$logoSrc = 'data:image/png;base64,' . $logoData;
?>

        <div class="invoice-box">

            <table width="100%" cellpadding="0" cellspacing="0" style="
    background:#fffdf5;
    border-bottom:4px solid #d4af37;
    margin-bottom:10px;
">
                <tr>
                    <!-- LOGO -->
                    <td width="15%" align="center" style="padding:12px;">
                        <img src="<?= $logoSrc ?>" style="width:90px;">
                    </td>

                    <!-- CENTER TEXT -->
                    <td width="85%" align="center" style="padding:12px 10px;">
                        <h2 style="
                margin:0;
                color:#7b1e1e;
                font-size:20px;
                font-weight:900;
                letter-spacing:4px;
            ">
                            R.P. JEWELLERS & SONS
                        </h2>

                        <!--            <p style="-->
                        <!--    margin:6px 0 2px;-->
                        <!--    font-size:10px;-->
                        <!--    font-weight:700;-->
                        <!--    color:#7b1e1e;-->
                        <!--">-->
                        <!--                Shree Rameshwar Prasad Sonar-->
                        <!--            </p>-->

                        <p style="
                margin:2px 0;
                font-size:12px;
                font-weight:600;
                color:#7b1e1e;
            "><b>Shree Rameshwar Prasad Sonar</b> <br>
                            <b>GSTIN:</b> 19BXRPP1193E1ZO <b>PAN No.</b> BXRPP1193E
                        </p>
                    </td>
                </tr>
            </table>



            <div class="info-box">
                <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse; font-size:9px;">
                    <tr>
                        <!-- LEFT : CUSTOMER DETAILS -->
                        <td width="50%" valign="top" style="padding-right:6px;">
                            <h5 style="font-size:11px;margin-bottom:4px;">Supplier Details</h5>

                            <p style="margin:2px 0; font-weight: 600">Invoice No:
                                <?= $invoice['invoice_no'] ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">Name:
                                <?= $supplier ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">Phone:
                                <?= $supplier_phone ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">Address:
                                <?= $supplier_address ?>, <?= $supplier_city ?>, <?= $supplier_state ?> -
                                <?= $supplier_pin ?>
                            </p>

                            <p style="margin:2px 0; font-weight: 600">PAN:
                                <?= $supplier_pan ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">GST:
                                <?= $supplier_gst ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">Date:
                                <?= $added_date ?>
                            </p>
                            <p style="margin:2px 0; font-weight: 600">State Code:
                                <?= $state_code ?>
                            </p>

                        </td>

                        <!-- RIGHT : COMPANY + BANK DETAILS -->
                        <td width="50%" valign="top" style="padding-left:6px;border-left:1px dashed #c9a84e;">

                            <h5 style="font-size:11px;margin-bottom:4px;">Company Details</h5>




                            <div style="font-size:11px; line-height:1.3;">
                                <strong>Bank Details:<br>
                                    A/C : R P JEWELLERS & SONS<br>
                                    A/C NO : 50200065493711 <br>
                                    BRANCH : BURDWAN ROAD,SILIGURI <br>
                                    IFSC CODE : HDFC0009521 </strong><br><br>
                            </div>

                        </td>
                    </tr>
                </table>
            </div>


            <div class="items-wrapper">

                <!-- ITEMS (SCROLLABLE) -->
                <div class="items-scroll">
                    <table class="table-invoice">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Category</th>
                                <th>Gross</th>
                                <th>Net</th>
                                <th>Rate</th>
                                <th>Making</th>
                                <th>Stone</th>
                                <th>HM</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td><?= $invoice['item_name'] ?></td>
                                <td><?= $invoice['category'] ?></td>
                                <td><?= number_format($invoice['gross_weight'],3) ?></td>
                                <td><?= number_format($invoice['net_weight'],3) ?></td>
                                <td><?= number_format($invoice['rate'],2) ?></td>
                                <td><?= number_format($invoice['making_value'],2) ?></td>
                                <td><?= number_format($invoice['stone_value'],2) ?></td>
                                <td><?= number_format($invoice['hm_value'],2) ?></td>
                                <td><?= number_format($subtotal,2) ?></td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- TOTAL (FIXED AT BOTTOM) -->
                <table class="table-invoice total-table">
                    <tr>
                        <td colspan="8"><strong>TOTAL</strong></td>
                        <td><strong>
                                <?= number_format($items_subtotal, 2) ?>
                            </strong></td>
                    </tr>
                </table>

            </div>

            <table width="100%" cellpadding="6" cellspacing="0" style="border-collapse:collapse; font-size:13px;">
                <tr>
                    <!-- LEFT : CUSTOMER DETAILS -->
                    <td width="50%" valign="top">

                        <div class="left-box">
                            <!-- <div class="row"><strong>UPI:</strong> ₹
                                <?= number_format($payments['UPI'], 2) ?>
                            </div>
                            <div class="row"><strong>Bank:</strong> ₹
                                <?= number_format($payments['Bank'], 2) ?>
                            </div>
                            <div class="row"><strong>Metal:</strong> ₹
                                <?= number_format($metal, 2) ?>
                            </div>
                            <div class="row"><strong>Cash:</strong> ₹
                                <?= number_format($payments['Cash'], 2) ?>
                            </div>
                            <div class="row"><strong>Dues:</strong> ₹
                                <?= number_format($dues, 2) ?>
                            </div> -->


                            <table class="table-invoice">
                                <thead>
                                    <tr>
                                        <th>UPI:</th>
                                        <th>Cheque:</th>
                                        <th>Metal:</th>
                                        <th>Cash:</th>
                                        <th>Card:</th>
                                    </tr>
                                </thead>

                                <tbody>

                                    <tr>
                                        <td>₹ <?= number_format($payments['UPI'], 2) ?></td>
                                        <td>₹ <?= number_format($payments['Cheque'], 2) ?></td>
                                        <td>₹ <?= number_format($payments['Metal'], 2) ?></td>
                                        <td>₹ <?= number_format($payments['Cash'], 2) ?></td>
                                        <td>₹ <?= number_format($payments['Card'], 2) ?></td>
                                    </tr>
                                </tbody>

                            </table>
                            <div class="total-words" style="font-weight:bold; font-size:13px;">
                                Total :
                                <?= numberToWords($grand_total) ?> Only
                            </div>
                        </div>
                    </td>

                    <!-- RIGHT : INVOICE DETAILS -->
                    <td width="50%" valign="top">
                        <div class="right-box">
                            <table>

                                <!-- SUBTOTAL -->
                                <tr>
                                    <td>Total :</td>
                                    <td>₹ <?= number_format($subtotal, 2) ?></td>
                                </tr>

                                <?php if ($state == 'west bengal'): ?>

                                <!-- NORMAL GST -->
                                <tr>
                                    <td>C-GST 1.5% :</td>
                                    <td>₹ <?= number_format($cgst, 2) ?></td>
                                </tr>
                                <tr>
                                    <td>S-GST 1.5% :</td>
                                    <td>₹ <?= number_format($sgst, 2) ?></td>
                                </tr>

                                <!-- HM GST -->
                                <tr>
                                    <td>HM CGST 9% :</td>
                                    <td>₹ <?= number_format($hm_cgst, 2) ?></td>
                                </tr>
                                <tr>
                                    <td>HM SGST 9% :</td>
                                    <td>₹ <?= number_format($hm_sgst, 2) ?></td>
                                </tr>

                                <?php else: ?>

                                <!-- NORMAL GST -->
                                <tr>
                                    <td>I-GST 3% :</td>
                                    <td>₹ <?= number_format($igst, 2) ?></td>
                                </tr>

                                <!-- HM GST -->
                                <tr>
                                    <td>HM IGST 18% :</td>
                                    <td>₹ <?= number_format($hm_igst, 2) ?></td>
                                </tr>

                                <?php endif; ?>

                                <!-- FINAL -->
                                <tr>
                                    <td>Final Amount :</td>
                                    <td>₹ <?= number_format($final, 2) ?></td>
                                </tr>

                                <tr>
                                    <td>Round Off :</td>
                                    <td>₹ <?= number_format($round_off, 2) ?></td>
                                </tr>

                                <tr style="font-size:14px; font-weight:bold;">
                                    <td>Grand Total :</td>
                                    <td>₹ <?= number_format($grand_total, 2) ?></td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>

            <div class="sign-area">
                <table width="100%">
                    <tr>
                        <!-- LEFT : CUSTOMER DETAILS -->
                        <td width="50%" valign="top">
                            <div class="sign-box">
                                ___________________________<br>Customer Signature
                            </div>
                        </td>

                        <!-- RIGHT : INVOICE DETAILS -->
                        <td width="50%" valign="top" style="padding-left: 40px;">
                            <div class="sign-box">
                                ___________________________<br>For R P JEWELLERS & SONS
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="footer-note">
                <p><strong>Visit Us:</strong> <strong>New Cinema Rd, Ward 28, Deshbandhu Para, Siliguri, West Bengal
                        734004</strong> <br>
                    <strong>Phone:</strong> <strong><a href="tel:+91 96415 77702">+91 96415 77702</a></strong> |
                    <strong><a href="tel:+91 97495 76542">+91 97495 76542</a></strong>
                </p>
                <div style="text-align:right; font-size:10px; margin-top:5px;">
                    <strong>Invoice Time:</strong> <?= $formatted_time ?>
                </div>
            </div>






        </div>
        <div style="text-align:center; margin:15px 0;">

           <a href="stock_invoice.php?id=<?= $id ?>&download=1"
    style="padding:8px 20px; background:#7b1e1e; color:#fff; text-decoration:none; margin-right:10px; display:inline-block;">
    Download PDF
</a>


        </div>
    </div>
</div>

<?php include 'include/footer.php'; ?>