<?php include '../includes/config.php'; ?>
<?php
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<?php
include '../includes/config.php';


if (isset($_GET['invoice_no']) && !empty($_GET['invoice_no'])) {
    $invoice_number = $_GET['invoice_no'];

    $invoice_number = intval($invoice_number);

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

    if ($row_customer) {
$stmt_products = $conn->prepare("
    SELECT ss.*, p.name AS product_name
    FROM return_sale ss
    JOIN products p ON ss.product_id = p.id
    WHERE ss.invoice = :invoice_number
");

        $stmt_products->bindParam(':invoice_number', $invoice_number, PDO::PARAM_INT);
        $stmt_products->execute();
    } else {
        echo "No data found for the provided invoice number.";
        exit;
    }
} else {
    echo "No invoice number provided.";
    exit;
}

$stmt = $conn->query("SELECT * FROM companies ORDER BY id DESC LIMIT 1");
$company = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!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>
        /* ================== General Styles ================== */
        body {
            font-family: Consolas, Arial, sans-serif;
            background-color: #fff;
            padding: 0;
            margin: 0;
        }

        .container {
            width: 76mm;
            /* safe margin for 80mm printer */
            max-width: 76mm;
            margin: 0 auto;
            padding: 0;
            box-sizing: border-box;
        }

        h1,
        h2,
        h3,
        h4,
        p {
            text-align: center;
            color: #000;
            margin: 0;
            padding: 1px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            word-break: break-word;
            font-size: 10px;
        }

        table td,
        table th {
            padding: 0 1px;
            /* minimal padding */
            border: 1px solid #000;
            font-size: 10px;
            text-align: left;
            word-wrap: break-word;
            overflow-wrap: break-word;
            white-space: normal;
        }

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

        /* Column widths */
        td:nth-child(1),
        th:nth-child(1) {
            width: 12px;
        }

        /* Sr # */
        td:nth-child(2),
        th:nth-child(2) {
            max-width: 45px;
        }

        /* Item */
        td:nth-child(3),
        th:nth-child(3) {
            max-width: 20px;
        }

        /* Size */
        td:nth-child(4),
        th:nth-child(4) {
            max-width: 20px;
        }

        /* QTY */
        td:nth-child(5),
        th:nth-child(5) {
            max-width: 25px;
        }

        /* Price */
        td:nth-child(6),
        th:nth-child(6) {
            max-width: 25px;
        }

        /* S.Tax */
        td:nth-child(7),
        th:nth-child(7) {
            max-width: 25px;
        }

        /* Total */

        .total {
            text-align: right;
            font-weight: bold;
            margin-top: 1px;
            margin-bottom: 1px;
            font-size: 10px;
            margin-right: 0.1em;
        }

        .image_logo {
            display: block;
            margin: 0 auto;
            width: 50px;
        }

        /* ================== Print Styles ================== */
        @media print {
            @page {
                size: 80mm auto;
                margin: 0;
            }

            body {
                margin: 0;
                padding: 0;
                width: 100%;
                background: #fff;
            }

            .container {
                width: 76mm;
                max-width: 76mm;
                margin: 0 auto;
                padding: 0;
                box-sizing: border-box;
            }

            table {
                width: 100%;
                border-collapse: collapse;
                table-layout: fixed;
                word-break: break-word;
                font-size: 10px;
            }

            table td,
            table th {
                padding: 0 1px;
                border: 1px solid #000;
                font-size: 10px;
                white-space: normal;
                word-wrap: break-word;
                overflow-wrap: break-word;
            }

            td:nth-child(1),
            th:nth-child(1) {
                width: 12px;
            }

            td:nth-child(2),
            th:nth-child(2) {
                max-width: 45px;
            }

            td:nth-child(3),
            th:nth-child(3) {
                max-width: 20px;
            }

            td:nth-child(4),
            th:nth-child(4) {
                max-width: 20px;
            }

            td:nth-child(5),
            th:nth-child(5) {
                max-width: 25px;
            }

            td:nth-child(6),
            th:nth-child(6) {
                max-width: 25px;
            }

            td:nth-child(7),
            th:nth-child(7) {
                max-width: 25px;
            }

            h1,
            h2,
            h3,
            h4,
            p {
                font-size: 10px;
                padding: 1px;
            }

            .total {
                font-size: 10px;
                margin-right: 0.1em;
            }

            .image_logo {
                width: 50px;
            }

            #back-link {
                display: none !important;
                visibility: hidden;
            }
        }
    </style>
</head>
<a href="../list_return_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-size: 21px; 
    font-weight:bold;
    display: flex; 
    align-items: center; 
    justify-content: center; 
    text-align: center; 
    margin: 0; 
    position: relative; 
    padding-left: 20px;
">
    <?php if (!empty($company['logo'])): ?>
        <!-- <img class="image_logo" src="../<?= htmlspecialchars($company['logo']) ?>" style="
            position: absolute; 
            left: 0; 
            width: 50px; 
            top: 50%; 
            padding-left: -2px;
            transform: translateY(-50%);
        " alt="Logo"> -->
    <?php endif; ?>

    <div style="
        display: flex; 
        flex-direction: column; 
        align-items: center; 
        width: 100%;
    ">
        <?php if (!empty($company['name'])): ?>
            <span><?= htmlspecialchars($company['name']) ?></span>
        <?php endif; ?>
    </div>
</h3>

<h4 style="display: flex; flex-direction: column; align-items: center; text-align: center; font-size: 13px; font-weight:bold; margin-top: 4px; margin-bottom:2px;">
    <?php if (!empty($company['address'])): ?>
        <span>Address: <?= htmlspecialchars($company['address']) ?></span><br>
    <?php endif; ?>

 <?php if (!empty($company['phone']) || !empty($company['email'])): ?>
    <span>
        <?php if (!empty($company['phone'])): ?>
            Phone: <?= htmlspecialchars($company['phone']) ?>
        <?php endif; ?>

        <?php if (!empty($company['phone']) && !empty($company['email'])): ?>
            &nbsp; | &nbsp;
        <?php endif; ?>

        <?php if (!empty($company['email'])): ?>
            Email: <?= htmlspecialchars($company['email']) ?>
        <?php endif; ?>
    </span>
<?php endif; ?>

</h4>

        <!-- <p style="align-items: center; text-align: center;">ESTIMATE
        </p> -->
        <h1 style="display: flex; flex-direction: column; align-items: center; text-align: center; font-size: 13px;"><?php echo  date("l"); ?> &nbsp; <?php echo date("d/m/Y"); ?> &nbsp; <?php date_default_timezone_set('Asia/Karachi');
                                                                                                                                                                                            $current_time = date('h:i A');
                                                                                                                                                                                            echo $current_time; ?></h1>
        <p style="font-size: 13px;"><b style="color: red;">   Return Invoice: <?php echo intval($invoice_number) ?></b> </p>
        <!-- / <b id="salesMan" style="cursor: pointer;" onclick="updateSalesMan()">SaleMan: </b><?php echo htmlspecialchars($row_customer['sales_man']); ?></p> -->

        <p style="font-size: 13px;"><b>Customer Name:<?php echo $row_customer['name']; ?> </b></p>
        <!--<p style="font-size: 14px;"><b>Customer Phone: <?php echo $row_customer['customer_phone']; ?></b></p>-->
        <script>
            function updateSalesMan() {
                var newSalesMan = prompt("Please enter the new SalesMan name:");

                if (newSalesMan) {
                    var invoiceNumber = <?php echo json_encode($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) {
                            if (xhr.status === 200) {
                                alert(xhr.responseText);
                                location.reload();
                            } else {
                                alert("Error updating salesman: " + xhr.statusText);
                            }
                        }
                    };
                    xhr.send("invoice_number=" + invoiceNumber + "&sales_man=" + encodeURIComponent(newSalesMan));
                }
            }
        </script>

       <table> 
    <thead>
        <tr>
            <th>#</th>
            <th>Item</th>
            <!-- <th>Brand Name</th> -->
          <th>Return QTY</th>
            <th>Price</th>
            <th>Total</th>
        </tr>
    </thead>

    <tbody>
         <?php
        $sr_number = 1;
        $total_qty = 0;
        $total_order_tax = 0;
        $total_amount_with_tax = 0;
        $order_tax_percentage = 0;

        while ($row_product = $stmt_products->fetch(PDO::FETCH_ASSOC)) {
            $exclusive_value = floatval($row_product['total_amount']);
            $sales_tax_value = ($exclusive_value * $order_tax_percentage) / 100;
            $total_with_tax = $exclusive_value + $sales_tax_value;

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

            // Calculate total quantity
            $qty = floatval($row_product['sale_qty']);
            $total_qty += $qty;
        ?>
            <tr>
                <td><?php echo $sr_number++; ?></td>
                <td><?php echo $row_product['product_name']; ?></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 number_format($total_with_tax, 2); ?></td>
            </tr>
        <?php } ?>
    </tbody>
</table>
        <?php
include '../includes/config.php';

// Check if the invoice number is provided in the URL
if (isset($_GET['invoice_no']) && !empty($_GET['invoice_no'])) {
    $invoice_number = $_GET['invoice_no'];

    // Sanitize the input to prevent SQL injection
    $invoice_number = intval($invoice_number);

    // Get the customer details
    $stmt_customer = $conn->prepare("SELECT contacts.name FROM contacts
    INNER JOIN return_sale ON contacts.id = return_sale.customer_id
    WHERE return_sale.invoice = :invoice_number;");
    $stmt_customer->bindParam(':invoice_number', $invoice_number, PDO::PARAM_INT);
    $stmt_customer->execute();
    $row_customer = $stmt_customer->fetch(PDO::FETCH_ASSOC);

    // Check if customer details are found for the given invoice
    if ($row_customer) {
        // Get the products in the bill
        $stmt_products = $conn->prepare("SELECT SUM(total_amount) as total_amount_sum, 
                                                SUM(net_cash) as net_cash_sum, 
                                                (discount) AS discount_sum, 
                                                SUM(order_tax) AS order_tax_sum, 
                                                SUM(sale_qty) AS Total_sale_qty
                                         FROM return_sale
                                         WHERE return_sale.invoice = :invoice_number");
        $stmt_products->bindParam(':invoice_number', $invoice_number, PDO::PARAM_INT);
        $stmt_products->execute();
        $row_products = $stmt_products->fetch(PDO::FETCH_ASSOC);
    } else {
        echo "No data found for the provided invoice number.";
        exit;
    }
} else {
    echo "No invoice number provided.";
    exit;
}
?>



       <div class="total">
    Total Return Qty: <?php echo htmlspecialchars($row_products['Total_sale_qty']); ?>
</div>
<div class="total">
    Total Return Amount: <?php echo htmlspecialchars($row_products['total_amount_sum']); ?>
</div>

        <div class="total">

        </div>

        <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";
        window.print();
        printButton.style.display = "block";
    }
</script>

</html>