<!DOCTYPE html>
<html lang="en">
<?php include 'includes/head.php'; ?>

<body>

    <div id="global-loader">
        <div class="whirly-loader"> </div>
    </div>


    <!-- Main Wrapper -->
    <div class="main-wrapper">

        <!-- Header -->
        <?php include './includes/navbar.php'; ?>
        <!-- /Header -->

        <?php $page = 'product-list';
        include './includes/sidebar.php'; ?>

        <div class="page-wrapper">
            <div class="content">
                <div class="page-header">
                    <div class="add-item d-flex">
                        <div class="page-title">
                            <h4>Invoice Report </h4>
                            <h6>Manage Your Invoice Report</h6>
                        </div>
                    </div>
                    <ul class="table-top-head">
                        <li>
                            <a id="pdfButton" data-bs-toggle="tooltip" data-bs-placement="top" title="Pdf" href="javascript:void(0)">
                                <img src="images/pdf.svg" alt="img">
                            </a>
                        </li>
                        <li>
                            <a data-bs-toggle="tooltip" data-bs-placement="top" title="Excel"><img src="images/excel.svg" alt="img"></a>
                        </li>
                        <li>
                            <a data-bs-toggle="tooltip" data-bs-placement="top" title="Print"><i data-feather="printer" class="feather-rotate-ccw"></i></a>
                        </li>
                        <li>
                            <a data-bs-toggle="tooltip" data-bs-placement="top" title="Refresh"><i data-feather="rotate-ccw" class="feather-rotate-ccw"></i></a>
                        </li>
                        <li>
                            <a data-bs-toggle="tooltip" data-bs-placement="top" title="Collapse" id="collapse-header"><i data-feather="chevron-up" class="feather-chevron-up"></i></a>
                        </li>
                    </ul>
                </div>


                <!-- Invoices -->
                <div class="main-container">
                    <!-- start from here -->
                    <div class="container p-2" style="max-width: 900px; background: #fff; border: 1px solid #ccc; font-family: 'Poppins', sans-serif;" id="customerContent">

                        <!-- Header -->
                        <div class="text-center mb-1">
                            <img src="images/Risav Dai a copy.png" alt="Logo" style="height: 90px;">
                            <h4 style="text-decoration: underline; font-weight: 700;">Proforma Invoice</h4>
                        </div>

                        <!-- Info Section -->
                        <div class="row justify-content-center mb-1" style="font-size: 14px;">
                            <div class="col-12">
                                <div class="row">
                                    <div class="col-6">
                                        <?php
                                        require_once 'php/databaseConnection.php';

                                        // Check if jobNumber is provided
                                        if (isset($_GET['jobNumber'])) {
                                            $jobNumber = $_GET['jobNumber'];
                                            $proformaNumber = $_GET['proformaNumber'] ?? '';


                                            // Database connection
                                            $mysqli = db_connect();
                                            if (!$mysqli) {
                                                die("Database connection failed: " . $mysqli->connect_error);
                                            }

                                            // Fetch job card details
                                            $stmt = $mysqli->prepare("SELECT customerName, customerAddress, contactNumber, customerVAT, jobNumber, jobDate, registerNumber, vinNumber, vehicleBrand, vehicleModel FROM jobCard WHERE jobNumber = ?");
                                            $stmt->bind_param("s", $jobNumber);
                                            $stmt->execute();
                                            $result = $stmt->get_result();

                                            // Check if record exists
                                            if ($result->num_rows > 0) {
                                                $jobCard = $result->fetch_assoc();
                                            } else {
                                                die("No record found for job number: " . htmlspecialchars($jobNumber));
                                            }
                                            $stmt->close();
                                            $mysqli->close();
                                        } else {
                                            die("Job number is required.");
                                        }
                                        ?>
                                        <p style="margin: 0; font-size: 12px;"><strong>Customer Name :-</strong> <?php echo $jobCard['customerName']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Customer Address :-</strong> <?php echo $jobCard['customerAddress']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Contact No. :-</strong> <?php echo $jobCard['contactNumber']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Customer’s VAT/PAN No. :-</strong> <?php echo $jobCard['customerVAT']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Bill Type :-</strong> Cash / Credit / Cheque / Digital Wallet</p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Job Order No. :-</strong> <?php echo $jobCard['jobNumber']; ?></p>
                                        <input type="text" id="jobNumber" value="<?php echo htmlspecialchars($jobCard['jobNumber']); ?>" hidden>
                                    </div>
                                    <div class="col-6 text-end">
                                        <p style="margin: 0; font-size: 12px;">
                                            <strong>Proforma No. :-</strong> <?php echo htmlspecialchars($proformaNumber); ?>
                                        </p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Proforma Date :-</strong> <?php echo $jobCard['jobDate']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Vehicle No. :-</strong> <?php echo $jobCard['registerNumber']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Vin No. :-</strong> <?php echo $jobCard['vinNumber']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Vehicle Brand :-</strong> <?php echo $jobCard['vehicleBrand']; ?></p>
                                        <p style="margin: 0; font-size: 12px;"><strong>Vehicle Model :-</strong> <?php echo $jobCard['vehicleModel']; ?></p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Table -->
                        <div class="table-responsive mb-3">
                            <table class="table table-condensed">
                                <thead class="thead-light">
                                    <tr>
                                        <th style="width: 5%;">S.N.</th>
                                        <th style="width: 15%;">H.S. Code</th>
                                        <th>Description</th>
                                        <th style="width: 10%;">Quantity</th>
                                        <th style="width: 15%; text-align: center;">Unit Price</th>
                                        <th style="width: 15%; text-align: center;">Net Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    require_once 'php/databaseConnection.php';

                                    // Database connection
                                    $mysqli = db_connect();
                                    if (!$mysqli) {
                                        die("Database connection failed: " . $mysqli->connect_error);
                                    }

                                    // Get job number from URL or use default
                                    $jobNumber = isset($_GET['jobNumber']) ? $mysqli->real_escape_string($_GET['jobNumber']) : 'JOBN7';

                                    $sn = 1; // Serial number starts from 1

                                    // Define all queries and their types
                                    $queries = [
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM mainParts WHERE jobNumber = ? AND category = 'Lubricant'",
                                            "label" => "Lubricants"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM mainParts WHERE jobNumber = ? AND category = 'Labour'",
                                            "label" => "Labours"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM mainParts WHERE jobNumber = ? AND category = 'Dent/Paint'",
                                            "label" => "Dents/Paint"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM mainParts WHERE jobNumber = ? AND category = 'Spare Parts'",
                                            "label" => "Spares"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM customs WHERE jobNumber = ? AND category = 'Lubricant'",
                                            "label" => "Custom Lubricants"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM customs WHERE jobNumber = ? AND category = 'Labour'",
                                            "label" => "Custom Labours"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM customs WHERE jobNumber = ? AND category = 'Dent/Paint'",
                                            "label" => "Custom Dents/Paint"
                                        ],
                                        [
                                            "sql" => "SELECT type_code AS type, quantity, price, net_amount AS net FROM customs WHERE jobNumber = ? AND category = 'Spare Parts'",
                                            "label" => "Custom Spares"
                                        ]
                                    ];

                                    // Loop through all queries and print results
                                    foreach ($queries as $queryData) {
                                        $stmt = $mysqli->prepare($queryData['sql']);
                                        $stmt->bind_param("s", $jobNumber);
                                        $stmt->execute();
                                        $result = $stmt->get_result();

                                        if ($result->num_rows > 0) {
                                            while ($row = $result->fetch_assoc()) {
                                                echo "<tr>";
                                                echo "<td>" . $sn++ . "</td>"; // Serial Number
                                                echo "<td></td>";
                                                echo "<td>" . htmlspecialchars($row['type']) . "</td>";       // Particulars
                                                echo "<td style='text-align: center;'>" . htmlspecialchars($row['quantity']) . "</td>"; // Quantity
                                                echo "<td style='text-align: center;'>" . htmlspecialchars($row['price']) . "</td>";    // Rate
                                                echo "<td style='text-align: center;'>" . htmlspecialchars($row['net']) . "</td>";      // Net Total
                                                echo "</tr>";
                                            }
                                        }

                                        $stmt->close();
                                    }

                                    // Close DB connection
                                    $mysqli->close();
                                    ?>
                                </tbody>
                            </table>
                        </div>
                        <!-- Totals -->
                        <div class="row justify-content-end">
                            <div class="col-sm-6 col-md-5">
                                <?php
                                require_once 'php/databaseConnection.php';

                                // Database connection
                                $mysqli = db_connect();
                                if (!$mysqli) {
                                    die("Database connection failed: " . $mysqli->connect_error);
                                }

                                // Get job number
                                $jobNumber = isset($_GET['jobNumber']) ? $mysqli->real_escape_string($_GET['jobNumber']) : 'JOBN7';

                                // Prepare and execute the statement
                                $stmt = $mysqli->prepare("SELECT TotalBillAmount, vatAmount, discountAmount, netTotal, billNumber, billRemarks, totalPaid, totalPaidInWords, remainingAmount, paymentStatus FROM jobCard WHERE jobNumber = ?");
                                $stmt->bind_param("s", $jobNumber);
                                $stmt->execute();
                                $result = $stmt->get_result();

                                $paymentInWords = ''; // Default value
                                if ($result->num_rows > 0) {
                                    $row = $result->fetch_assoc();
                                    $paymentInWords = $row['totalPaidInWords'];
                                ?>
                                    <table class="table table-bordered compact-table" style="font-size: 14px;">

                                        <tr>
                                            <th style="width: 60%;"><strong>Grand Total Amount</strong></th>
                                            <td><strong><?php echo htmlspecialchars($row['TotalBillAmount']); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <th>Discount</th>
                                            <td><?php echo htmlspecialchars($row['discountAmount']); ?></td>
                                        </tr>
                                        <tr>
                                            <th>VAT (13%)</th>
                                            <td><?php echo htmlspecialchars($row['vatAmount']); ?></td>
                                        </tr>
                                        <tr>
                                            <th><strong>Grand Total Amount</strong></th>
                                            <td><strong><?php echo htmlspecialchars($row['netTotal']); ?></strong></td>
                                        </tr>

                                    </table>
                                <?php
                                } else {
                                    echo '<div class="d-flex justify-content-center"><p>No records found for this job number.</p></div>';
                                }

                                // Close connections
                                $stmt->close();
                                $mysqli->close();
                                ?>
                            </div>
                        </div>

                        <!-- Footer -->
                        <div class="row mt-4" style="font-size: 14px;">
                            <div class="col-md-6">
                                <p><strong>Payment in words :-</strong> <?php echo $paymentInWords ? htmlspecialchars($paymentInWords) : 'N/A'; ?></p>
                                <p><strong>Received By :-</strong> ____________________</p>
                            </div>
                            <div class="col-md-6 text-end">
                                <p><span style="color: #E51E2A;"><strong>For- Crossways Autovilla</strong></span></p>
                                &nbsp;
                                <p><strong>Accounts Department</strong></p>
                            </div>
                        </div>
                        <!-- Horizontal line here -->
                        <hr style="border-top: 1px solid #999; margin: 5px 1px;">

                        <div class="row mt-1" style="font-size: 14px;">
                            <div class="col-md-14 text-center">
                                <p style="font-size: 0.6em; margin: 0;"><strong>Note :-</strong> Proforma Invoice is raised as per request of customer and holds no legal rights for legal claims.</p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="text-center">
                    <div class="mb-0">
                        <svg width="180" height="65" viewBox="0 0 300 80" xmlns="http://www.w3.org/2000/svg">
                            <g fill="none" fill-rule="evenodd">
                                <!-- Shopping Bag Icon -->
                                <rect x="10" y="10" width="50" height="50" rx="10" fill="#FFA64D" />
                                <path d="M25 15a10 10 0 0 1 20 0" stroke="#0D1B40" stroke-width="3" fill="none" />
                                <circle cx="35" cy="35" r="14" fill="#0D1B40" />

                                <!-- Dollar Symbol Inside Circle -->
                                <text x="31" y="40" font-family="Arial, sans-serif" font-size="16" fill="white" font-weight="bold">$</text>

                                <!-- Text "ArthaVidhi" -->
                                <text x="70" y="50" font-family="Poppins, sans-serif" font-size="40" fill="#0D1B40" font-weight="bold">ArthaVidhi</text>

                                <!-- "SOFT" Text -->
                                <text x="230" y="10" font-family="Poppins, sans-serif" font-size="22" fill="#FFA64D" font-weight="900">SOFT</text>
                            </g>
                        </svg>
                    </div>
                </div>
            </div>
        </div>
        <!-- /Invoices -->
    </div>
    </div>
    </div>
    <!-- /Main Wrapper -->
    <div class="customizer-links" id="setdata">
        <ul class="sticky-sidebar">
            <li class="sidebar-icons">
                <a href="#" class="navigation-add" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-original-title="Theme">
                    <i data-feather="settings" class="feather-five"></i>
                </a>
            </li>
        </ul>
    </div>


    <!-- jQuery -->
    <script src="js/jquery-3.7.1.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Feather Icon JS -->
    <script src="js/feather.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Slimscroll JS -->
    <script src="js/jquery.slimscroll.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Datatable JS -->
    <script src="js/jquery.dataTables.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>
    <script src="js/dataTables.bootstrap5.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Datetimepicker JS -->
    <script src="js/moment.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>
    <script src="js/bootstrap-datetimepicker.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Daterangepikcer JS -->
    <script src="js/moment.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>
    <script src="js/daterangepicker.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Bootstrap Core JS -->
    <script src="js/bootstrap.bundle.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Summernote JS -->
    <script src="js/summernote-bs4.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Select2 JS -->
    <script src="js/select2.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Sweetalert 2 -->
    <script src="js/sweetalert2.all.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>
    <script src="js/sweetalerts.min.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>

    <!-- Custom JS -->
    <script src="js/script.js" type="d4e35c9ac780cf7a658c1972-text/javascript"></script>


    <script src="js/rocket-loader.min.js" data-cf-settings="d4e35c9ac780cf7a658c1972-|49" defer=""></script>

    <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>
</body>
<style>
    .table-condensed td,
    .table-condensed th {
        padding: 3px 5px !important;
        /* Reduce vertical and horizontal padding */
        font-size: 6px;
        /* Smaller font for more content fit */
        line-height: 1.1;
    }

    .table-condensed {
        border-collapse: collapse;
        /* Remove spacing between cells */
    }

    .table-condensed tr {
        margin: 0;
    }
</style>
<style>
    .compact-table {
        font-size: 12px;
        /* Smaller text */
    }

    .compact-table th,
    .compact-table td {
        padding: 2px 4px !important;
        /* Less vertical & horizontal space */
        vertical-align: middle;
    }

    .compact-table th {
        font-weight: 600;
    }

    .table-condensed tr {
        margin: 0;
    }
</style>
<script>
    document.getElementById('pdfButton').addEventListener('click', function() {
        generatePDF();
    });

    function generatePDF() {
        const {
            jsPDF
        } = window.jspdf;
        const pdfWidth = 210; // A4 width in mm
        const pdfHeight = 297; // A4 height in mm
        const marginLeft = 10;
        const marginRight = 10;
        const marginTop = 10;
        const contentWidth = pdfWidth - marginLeft - marginRight;
        const doc = new jsPDF("p", "mm", "a4");

        html2canvas(document.querySelector("#customerContent"), {
            scale: 2
        }).then(canvas => {
            const imgData = canvas.toDataURL("image/png");
            let imgWidth = contentWidth;
            let imgHeight = (canvas.height * imgWidth) / canvas.width;
            const maxHeight = pdfHeight - marginTop;
            if (imgHeight > maxHeight) imgHeight = maxHeight;

            doc.addImage(imgData, "PNG", marginLeft, marginTop, imgWidth, imgHeight);
            const blobUrl = doc.output('bloburl');
            const win = window.open(blobUrl, '_blank');
            if (!win) alert("Popup blocked! Please allow popups for this site.");
        });
    }
</script>

</html>