<?php
include '../includes/config.php';
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<?php
$stmt_invoice = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM stock_sale;");
$stmt_invoice->execute();
$row_invoice = $stmt_invoice->fetch(PDO::FETCH_ASSOC);
$invoice_number = $row_invoice['max_invoice'];

$stmt_customer = $conn->prepare("SELECT contacts.name, stock_sale.date_sale, stock_sale.sales_man, stock_sale.order_tax FROM contacts
INNER JOIN stock_sale ON contacts.id = stock_sale.customer_id
WHERE stock_sale.invoice = :invoice_number;");
$stmt_customer->bindParam(':invoice_number', $invoice_number);
$stmt_customer->execute();
$row_customer = $stmt_customer->fetch(PDO::FETCH_ASSOC);

$order_tax_percentage = floatval($row_customer['order_tax']);

$stmt_products = $conn->prepare("
    SELECT 
        ss.*, 
        b.name AS brand_name,
        c.product_color,
        s.product_size
    FROM stock_sale ss
    JOIN products p ON ss.product_id = p.id
    JOIN brands b ON p.brand_id = b.id
    LEFT JOIN purchase_lines pl 
        ON pl.id = (
            SELECT pl2.id 
            FROM purchase_lines pl2 
            WHERE pl2.product_id = ss.product_id
            ORDER BY pl2.id DESC
            LIMIT 1
        )
    LEFT JOIN colors c ON pl.color_id = c.id
    LEFT JOIN sizes s ON pl.size_id = s.id
    WHERE ss.invoice = :invoice_number
");


$stmt_products->bindParam(':invoice_number', $invoice_number);
$stmt_products->execute();

$total_order_tax = 0; 
$total_amount_with_tax = 0; 
?>


<!DOCTYPE html>
<html>

<head>
    <title>Sales Receipt</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Crimson+Text&display=swap" rel="stylesheet">
<style>
@page {
    size: A4 portrait;
    margin: 0;
}

body {
    font-family: Consolas, Arial, sans-serif;
    background-color: #f5f5f5;
    padding: 0;
    margin: 0;
}

.container {
    width: 210mm;
    height: 297mm;
    margin: 0 auto;
    padding: 20mm;
    background-color: #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    border: 1px solid #000;
    border-radius: 5px;
    overflow: hidden;
    box-sizing: border-box;
}

h1, h2, h3 {
    text-align: center;
    color: #333;
    background-color: #f2f2f2;
    padding: 10px;
    margin: 0;
    border-bottom: 2px solid #000;
    font-weight: bold;
}

p {
    text-align: left;
    color: #333;
    background-color: #f2f2f2;
    padding: 5px;
    margin: 0;
    border-bottom: 1px solid #000;
     font-weight: bold;
}
  .div_box{
     text-align: left;
    color: #000;
    background-color: #f2f2f2;
    padding: 5px;
    margin: 0;
    border-bottom: 1px solid #000;
     font-weight: bold;
  }

.table-container {
    margin-top: 20px;
}

table {
    width: 100%;
    border-collapse: collapse;
    font-size: 15px;
}

table td, table th {
    padding: 10px;
    border: 1px solid #000;
    text-align: left;
     font-weight: bold;
}

table th {
    background-color: #f2f2f2;
    font-weight: bold;
}

.total {
    text-align: right;
    font-weight: bold;
    font-size: 16px;
    margin-top: 10px;
}

.logo {
    width: 100px;
    margin: 10px auto;
    display: block;
}

/* Print Styles */
@media print {
    @page {
        size: A4 portrait;
        margin: 0;
    }

    body, html {
        background: #fff;
        margin: 0;
        padding: 0;
    }

    .container {
        width: 100%;
        height: auto;
        padding: 10mm;
        box-shadow: none;
        border: none;
    }

    h1, h2, h3 {
        padding: 5px;
        border-bottom: 2px solid #000;
       font-size: 15px;
    }

    table td, table th {
        padding: 8px;
        font-size: 15px;
    }

    .total {
        font-size: 15px;
    }

    .logo {
        width: 80px;
    }

    #back-link, .no-print {
        display: none;
    }
}
</style>

</head>
<a href="../pos.php" id="back-link">Back POS</a>

<body>
    <div class="container" id="data">
        <!-- <div class="logo">
        <img src="invoice_logo.jpg">
        </div> -->
        <h3 style="
        font-family: Consolas, Arial, sans-serif; 
        font-size: 28px; 
        font-weight:bold;
        display: flex; 
        align-items: center; 
        justify-content: center; 
        text-align: center; 
        margin: 0; 
        position: relative; 
        padding-left: 20px; /* Space for the logo */
    ">
        <!--    <img class="image_logo" src="logo.png" style="-->
        <!--    position: absolute; -->
        <!--    left: 0; -->
        <!--    width: 60px; -->
        <!--    top: 50%; -->
        <!--    padding-left: 5px;-->
        <!--    transform: translateY(-50%);-->
        <!--" alt="Logo">-->
            <div style="
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            width: 100%;
        ">
                <span>Pen Grid</span>
            </div>
        </h3>

        <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px;">
    
    <!-- Left Column: Customer Details -->
    <div style="flex: 1;">
<h4 class="div_box" style="font-size: 15px; font-weight: bold; margin: 0; display: flex; justify-content: space-between; align-items: center;">
    <!-- <span><?php echo date("H:i:s");  ?></span> -->
    <span style="font-weight: bold;"><?php echo date("l d/m/Y", strtotime($row_customer['date_sale'])); ?> / <?php echo date("h:i:s A");  ?></span>
</h4>
        <h4 class="div_box" style="font-size: 15px; margin: 2px 0;"><b>Invoice: <?php echo intval($invoice_number); ?></b></h4>
        <!--<p style="font-size: 14px; margin: 2px 0;">-->
        <!--    <b id="salesMan" style="cursor: pointer;" onclick="updateSalesMan()">SaleMan: </b><?php echo htmlspecialchars($row_customer['sales_man']); ?>-->
        <!--</p>-->
        <h4 class="div_box" style="font-size: 15px; margin: 2px 0; font-weight: bold;"><b>Customer Name: <?php echo htmlspecialchars($row_customer['name']); ?> </b></h4>
        <!-- <p style="font-size: 14px;"><b>Customer Phone: <?php echo $row_customer['customer_phone']; ?></b></p> -->
    </div>

    <!-- Right Column: Company Details -->
    <div style="flex: 1; text-align: right;">
        <h4 style="font-size: 15px; font-weight: bold; margin: 0;">
            <!--Address: 419/420 Pia Main Boulevard--><br>
          Phone: 0324-5246625 <br>
            
        </h4>
    </div>
</div>

        <script>
            function updateSalesMan() {
                // Prompt the user to enter a new salesman's name
                var newSalesMan = prompt("Please enter the new SalesMan name:");

                // Check if the user entered a value
                if (newSalesMan) {
                    // Prepare data to be sent to the PHP script
                    var invoiceNumber = <?php echo json_encode($invoice_number); ?>;

                    // Create an AJAX request to send the new salesman name and invoice number
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "update_salesman.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            // Check the response from the server
                            if (xhr.status === 200) {
                                alert(xhr.responseText); // Notify the user of success
                                // Refresh the page to show updated information
                                location.reload();
                            } else {
                                alert("Error updating salesman: " + xhr.statusText);
                            }
                        }
                    };
                    xhr.send("invoice_number=" + invoiceNumber + "&sales_man=" + encodeURIComponent(newSalesMan));
                }
            }
        </script>

 <table>
  <thead>
    <tr>
        <th>SR#</th> 
        <th>Item</th>
        <th>Brand Name</th>
        <th>Color</th>
        <th>Size</th>
        <th>QTY</th>
        <th>Price</th>
        <th>S.Tax (%)</th>
        <th>Total</th> 
    </tr>
</thead>


    <tbody>
        <?php
        $sr_number = 1;
        $total_qty = 0; // Total quantity counter
        $total_order_tax = 0;
        $total_amount_with_tax = 0;

        while ($row_product = $stmt_products->fetch(PDO::FETCH_ASSOC)) {
            // $exclusive_value = floatval($row_product['total_amount']);
            $exclusive_value = floatval($row_product['price']) * floatval($row_product['sale_qty']);

           $product_tax_percentage = floatval($row_product['sale_tax']);
$sales_tax_value = ($exclusive_value * $product_tax_percentage) / 100;
$total_with_tax = $exclusive_value + $sales_tax_value;


            $total_order_tax += $sales_tax_value;
            $total_amount_with_tax += $total_with_tax;

            $qty = floatval($row_product['sale_qty']); // Convert quantity to float
            $total_qty += $qty; // Accumulate total quantity
        ?>
          <tr>
    <td><?php echo $sr_number++; ?></td>
    <td><?php echo $row_product['product_name']; ?></td>
    <td><?php echo $row_product['brand_name']; ?></td>
    <td><?php echo $row_product['product_color']; ?></td>
    <td><?php echo $row_product['product_size']; ?></td>
    <td><?php echo $row_product['sale_qty'] . " " . $row_product['unit']; ?></td>
    <td><?php echo number_format($row_product['price'], 2); ?></td>
    <td>(<?php echo ($product_tax_percentage); ?>%) <br>  <?php echo number_format($sales_tax_value, 2); ?></td>
    <!-- <td><?php echo number_format($sales_tax_value, 2); ?></td> -->
    <td><?php echo number_format($total_with_tax, 2); ?></td>
</tr>

        <?php } ?>
    </tbody>

    
</table>


     <?php
include '../includes/config.php';

// Get the latest invoice number
$stmt_invoice = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM stock_sale;");
$stmt_invoice->execute();
$row_invoice = $stmt_invoice->fetch(PDO::FETCH_ASSOC);
$invoice_number = $row_invoice['max_invoice'];

// Get customer and order tax info
$stmt_customer = $conn->prepare("SELECT contacts.name, contacts.business_id, contacts.type, contacts.id, contacts.opening_balance, contacts.balance_status, stock_sale.order_tax
                                 FROM contacts
                                 INNER JOIN stock_sale ON contacts.id = stock_sale.customer_id
                                 WHERE stock_sale.invoice = :invoice_number;");
$stmt_customer->bindParam(':invoice_number', $invoice_number);
$stmt_customer->execute();
$row_customer = $stmt_customer->fetch(PDO::FETCH_ASSOC);

// Convert values
$customer_id = $row_customer['id'];
$opening_balance = floatval($row_customer['opening_balance']);
$balance_status = strtolower($row_customer['balance_status']); // 'yes' or 'no'
$order_tax_percentage = floatval($row_customer['order_tax']);

// Get products in current bill
$stmt_products = $conn->prepare("SELECT SUM(total_amount) AS total_amount_sum, 
                                        SUM(net_cash) AS net_cash_sum, 
                                        SUM(discount) AS discount_sum, 
                                        SUM(sale_qty) AS Total_sale_qty
                                 FROM stock_sale
                                 WHERE invoice = :invoice_number");
$stmt_products->bindParam(':invoice_number', $invoice_number);
$stmt_products->execute();
$row_products = $stmt_products->fetch(PDO::FETCH_ASSOC);

// Calculate tax
$order_tax_sum = ($row_products['total_amount_sum'] * $order_tax_percentage) / 100;

// Set default balances
$total_previous_balance = 0;
$due_balance = 0;

if ($balance_status === 'yes') {
    // Get previous balance from old sales
    $stmt_previous_balance = $conn->prepare("SELECT SUM(total_amount + order_tax - discount) AS previous_balance
                                             FROM stock_sale
                                             WHERE customer_id = :customer_id
                                             AND invoice < :invoice_number
                                             AND (total_amount + order_tax - discount) > 0");
    $stmt_previous_balance->bindParam(':customer_id', $customer_id);
    $stmt_previous_balance->bindParam(':invoice_number', $invoice_number);
    $stmt_previous_balance->execute();
    $row_previous_balance = $stmt_previous_balance->fetch(PDO::FETCH_ASSOC);
    $previous_balance = floatval($row_previous_balance['previous_balance'] ?? 0);

    // Get deposits and manual bills
    $stmt_cash_deposit = $conn->prepare("SELECT SUM(amount) AS cash_deposit_sum FROM cash_deposit WHERE user_id = :customer_id;");
    $stmt_cash_deposit->bindParam(':customer_id', $customer_id);
    $stmt_cash_deposit->execute();
    $cash_deposit_sum = floatval($stmt_cash_deposit->fetchColumn());

    $stmt_manual_bill = $conn->prepare("SELECT SUM(amount) AS manual_bill_sum FROM customer_bill_manual WHERE user_id = :customer_id;");
    $stmt_manual_bill->bindParam(':customer_id', $customer_id);
    $stmt_manual_bill->execute();
    $manual_bill_sum = floatval($stmt_manual_bill->fetchColumn());

    // Calculate total previous balance
    $total_previous_balance = $previous_balance + $opening_balance - ($cash_deposit_sum - $row_products['net_cash_sum']) + $manual_bill_sum;

    // Calculate due with previous balance
    $due_balance = ($row_products['total_amount_sum'] + $order_tax_sum)
                 - ($row_products['net_cash_sum'] + $row_products['discount_sum'])
                 + $total_previous_balance;
} else {
    // Calculate due without previous balance
    $due_balance = ($row_products['total_amount_sum'] + $order_tax_sum)
                 - ($row_products['net_cash_sum'] + $row_products['discount_sum']);
}
?>

<!-- Output results -->
<div class="total">
    Total Amount: <?php echo htmlspecialchars(number_format($row_products['total_amount_sum'], 2)); ?>
</div>

<?php if ($row_products['discount_sum'] > 0) : ?>
    <div class="total">
        Discount: <?php echo htmlspecialchars(number_format($row_products['discount_sum'], 2)); ?>
    </div>
<?php endif; ?>

<?php if ($balance_status === 'yes') : ?>
    <div class="total">
        Previous Balance: <?php echo htmlspecialchars(number_format($total_previous_balance, 2)); ?>
    </div>
<?php endif; ?>

<?php if ($row_products['net_cash_sum'] > 0) : ?>
    <div class="total">
        Net Receivable: <?php echo htmlspecialchars(number_format($row_products['net_cash_sum'], 2)); ?>
    </div>
<?php endif; ?>

<div class="total">
    Due Balance: <?php echo htmlspecialchars(number_format($due_balance, 2)); ?>
</div>
<?php
try {
    if ($balance_status === 'yes') {
        // echo "<pre>";
        // echo "DEBUG: Invoice number = " . $invoice_number . "\n";
        // echo "DEBUG: Customer ID = " . $customer_id . "\n";
        // echo "DEBUG: Total Previous Balance = " . $total_previous_balance . "\n";

        $stmt_check = $conn->prepare("SELECT COUNT(*) FROM reprint_previous_balance WHERE invoice = :invoice");
        $stmt_check->bindParam(':invoice', $invoice_number);
        $stmt_check->execute();
        $exists = $stmt_check->fetchColumn();

        // echo "DEBUG: Existing rows with this invoice = " . $exists . "\n";

        if ($exists == 0) {
            $stmt_insert = $conn->prepare("INSERT INTO reprint_previous_balance (customer_id, invoice, balance) VALUES (:customer_id, :invoice, :balance)");
            $stmt_insert->bindParam(':customer_id', $customer_id);
            $stmt_insert->bindParam(':invoice', $invoice_number);
            $stmt_insert->bindParam(':balance', $total_previous_balance);
            $stmt_insert->execute();

            // echo "DEBUG: Inserted new record.\n";
        } else {
            $stmt_update = $conn->prepare("UPDATE reprint_previous_balance SET balance = :balance WHERE invoice = :invoice");
            $stmt_update->bindParam(':balance', $total_previous_balance);
            $stmt_update->bindParam(':invoice', $invoice_number);
            $stmt_update->execute();

            // echo "DEBUG: Updated existing record.\n";
        }
        // echo "</pre>";
    }
} catch (PDOException $e) {
    echo "<pre>ERROR: " . $e->getMessage() . "</pre>";
}
?>



        <!-- <p style="align-items: center; font-weight:bold; text-align: center;">Goods Once Sold are not returnable
        </p> -->
        <h2>Thank You</h2>
        <!-- <p style="text-align:center; font-size:14px; font-weight:bold;">(Developed by IT Genesis)<br>webisite:itgenesis.net & ph: +92 308 4926007</p> -->
        <button onclick="printContent()">Print</button>
    </div>
</body>
<script>
    function printContent() {
        var container = document.querySelector(".container");
        var printButton = document.querySelector("button");
        printButton.style.display = "none"; // Hide the button

        window.print(); 

        setTimeout(function() {
            window.location.href = '../pos.php';
        }, 500); 
    }
</script>

</html>