<?php
include("../db/cn.php");
include("common/tx.php");
ob_start();
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

// Fetch order details from the database
$orderId = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE order_id = '$orderId'";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = floatval($order['net_amount']);
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = floatval($order['discount_amount']);
        $discounted = floatval($order['discounted']);
        $discountPer = $order['discount_per'];
        $cashAmount = floatval($order['cash_amount']);
        $changeAmount = floatval($order['change_amount']);
        $taxAmount = $order['tax_amount'];
        $cutting = floatval($order['cutting']);
        $loading = floatval($order['loading']);
        $ctn = floatval($order['ctn']);
        $bora = floatval($order['bora']);
        $vehicle_rent = floatval($order['vehicle_rent']);
        $pre = floatval($order['pre_amount']);
        $close = floatval($order['grand_amount']);
    }
}

$content = ob_get_clean();

// Handle exit and update customer balance
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['exit'])) {
    if (!empty($customerName) && $customerName != 'walkin') {
        $checkQuery = "SELECT 1 FROM creditor_closing WHERE creditor_name = '$customerName' LIMIT 1";
        $checkResult = mysqli_query($connection, $checkQuery);

        if (mysqli_num_rows($checkResult) > 0) {
            $updateQuery = "UPDATE creditor_closing SET remain_balance = $changeAmount WHERE creditor_name = '$customerName'";
            $updateResult = mysqli_query($connection, $updateQuery);
        } else {
            $insertQuery = "INSERT INTO creditor_closing (
                creditor_name, opening_cash, credit_sales, credit_recieved,
                remain_balance, date_time, login_user, user_role,
                outlet_name, outlet_address
            ) VALUES (
                '$customerName', 0, 0, 0, $changeAmount, NOW(), '$userName', '$userRole', '$outlet_name', '$outlet_address'
            )";
            $insertResult = mysqli_query($connection, $insertQuery);
        }
    }
    header("Location: mainpos.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Invoice | <?php echo htmlspecialchars($tx); ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary: #1e293b;
            --border: #e2e8f0;
            --bg-light: #f8fafc;
            --text: #0f172a;
            --text-muted: #64748b;
            --accent: #0f766e;
            --danger: #b91c1c;
            --success: #15803d;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #f1f5f9;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 40px 20px;
            color: var(--text);
        }

        .invoice {
            width: 210mm;
            max-width: 210mm;
            background: #ffffff;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            border-radius: 12px;
            overflow: hidden;
            position: relative;
        }

        /* ----- MODAL (screen only) ----- */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        .modal.active {
            display: flex;
        }
        .modal-dialog {
            background: white;
            border-radius: 12px;
            padding: 30px 25px;
            width: 90%;
            max-width: 380px;
            text-align: center;
            box-shadow: 0 15px 35px rgba(0,0,0,0.2);
        }
        .modal-dialog h2 {
            margin-bottom: 10px;
            font-size: 20px;
            color: #1e293b;
        }
        .modal-dialog p {
            font-size: 14px;
            color: #64748b;
            margin-bottom: 25px;
        }
        .modal-buttons {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .modal-btn {
            padding: 14px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .modal-btn.thermal {
            background: #0f172a;
            color: white;
        }
        .modal-btn.thermal:hover {
            background: #1e293b;
        }
        .modal-btn.a4 {
            background: #e2e8f0;
            color: #0f172a;
        }
        .modal-btn.a4:hover {
            background: #cbd5e1;
        }
        .modal-close {
            margin-top: 15px;
            background: transparent;
            border: none;
            color: #64748b;
            text-decoration: underline;
            cursor: pointer;
            font-size: 14px;
        }

        .invoice-header {
            background: var(--primary);
            color: white;
            padding: 24px 36px;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
        }

        .company-info h1 {
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -0.5px;
            margin-bottom: 4px;
        }

        .company-info .address {
            font-size: 13px;
            opacity: 0.85;
            line-height: 1.5;
        }

        .invoice-badge {
            text-align: right;
        }
        .invoice-badge .label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 2px;
            opacity: 0.8;
        }
        .invoice-badge .number {
            font-size: 24px;
            font-weight: 700;
            margin-top: 4px;
        }

        .invoice-body {
            padding: 36px 36px 24px;
        }

        .meta-row {
            display: flex;
            flex-wrap: wrap;
            gap: 30px;
            margin-bottom: 28px;
        }

        .meta-box {
            flex: 1;
            min-width: 180px;
        }
        .meta-box h3 {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-muted);
            margin-bottom: 10px;
            border-bottom: 1px solid var(--border);
            padding-bottom: 6px;
        }
        .meta-box p {
            font-size: 14px;
            line-height: 1.6;
            font-weight: 500;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 28px 0 20px;
        }

        .items-table thead th {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-muted);
            border-bottom: 2px solid var(--border);
            padding: 12px 8px;
            text-align: left;
        }
        .items-table thead th:last-child,
        .items-table thead th:nth-child(4),
        .items-table thead th:nth-child(5),
        .items-table thead th:nth-child(6) {
            text-align: right;
        }

        .items-table tbody td {
            padding: 14px 8px;
            border-bottom: 1px solid var(--border);
            font-size: 14px;
            vertical-align: top;
        }
        .items-table tbody td:last-child,
        .items-table tbody td:nth-child(4),
        .items-table tbody td:nth-child(5),
        .items-table tbody td:nth-child(6) {
            text-align: right;
        }

        .item-name {
            font-weight: 600;
            color: var(--text);
        }

        .totals-section {
            margin-top: 28px;
            display: flex;
            justify-content: flex-end;
        }
        .totals-grid {
            width: 320px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            font-size: 15px;
        }
        .totals-grid .row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
        }
        .totals-grid .row.total {
            font-weight: 700;
            font-size: 17px;
            border-top: 2px solid var(--primary);
            padding-top: 12px;
            margin-top: 4px;
        }
        .totals-grid .row.discount {
            color: var(--danger);
        }
        .totals-grid .row.payment {
            color: var(--success);
        }

        .exchange-policy {
            margin-top: 30px;
            background: var(--bg-light);
            border-radius: 8px;
            padding: 16px 20px;
            font-size: 13px;
            color: var(--text-muted);
            border: 1px solid var(--border);
        }
        .exchange-policy strong {
            color: var(--text);
            display: block;
            margin-bottom: 6px;
        }

        .footer {
            margin-top: 24px;
            text-align: center;
            font-size: 12px;
            color: var(--text-muted);
            border-top: 1px solid var(--border);
            padding-top: 20px;
        }

        .button-group {
            background: white;
            padding: 20px 36px;
            border-top: 1px solid var(--border);
            display: flex;
            gap: 14px;
            justify-content: flex-end;
        }
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            font-family: 'Inter', sans-serif;
        }
        .btn-primary {
            background: var(--primary);
            color: white;
        }
        .btn-primary:hover {
            background: #0f172a;
        }
        .btn-secondary {
            background: #e2e8f0;
            color: #334155;
        }
        .btn-secondary:hover {
            background: #cbd5e1;
        }

        @media screen and (max-width: 800px) {
            .invoice-header {
                flex-direction: column;
                gap: 16px;
            }
            .meta-row {
                flex-direction: column;
                gap: 20px;
            }
            .items-table thead {
                display: none;
            }
            .items-table tbody td {
                display: block;
                text-align: right;
                padding: 8px;
            }
            .items-table tbody td::before {
                content: attr(data-label);
                float: left;
                font-weight: 600;
                text-transform: uppercase;
                color: var(--text-muted);
            }
            .totals-grid {
                width: 100%;
            }
        }

        /* ================ PRINT STYLES ================ */
        @media print {
            /* Hide screen elements */
            .no-print, .modal, #printModal {
                display: none !important;
            }

            /* DEFAULT: A4/A5 layout (when body does NOT have .print-thermal) */
            body:not(.print-thermal) {
                background: white;
                padding: 0;
                margin: 0;
            }
            body:not(.print-thermal) .invoice {
                width: 100%;
                max-width: 100%;
                box-shadow: none;
                border-radius: 0;
                margin: 0;
                padding: 0;
            }
            body:not(.print-thermal) .invoice-body {
                padding: 15mm 15mm 10mm;
            }
            body:not(.print-thermal) .invoice-header {
                padding: 15mm 15mm 5mm;
            }
            @page {
                size: A4;
                margin: 15mm;
            }

            /* THERMAL PRINT LAYOUT - FIXED TOP SPACE */
            body.print-thermal {
                background: white;
                margin: 0;
                padding: 0;
            }
            body.print-thermal .invoice {
                width: 80mm;
                max-width: 80mm;
                box-shadow: none;
                border-radius: 0;
                margin: 0 auto;
                padding: 0;
                font-size: 10px;
                font-family: 'Courier New', monospace;
            }
            body.print-thermal .invoice-header {
                background: none !important;
                color: black;
                text-align: center;
                padding: 1mm 2mm 2mm;   /* reduced top padding */
                border-bottom: 1px dashed #000;
                flex-direction: column;
                gap: 1px;
            }
            body.print-thermal .company-info h1 {
                font-size: 14px;
                margin: 0;
                line-height: 1.2;
            }
            body.print-thermal .company-info .address {
                font-size: 10px;
                opacity: 1;
                margin: 0;
                line-height: 1.2;
            }
            body.print-thermal .invoice-badge {
                text-align: center;
                margin-top: 2px;
            }
            body.print-thermal .invoice-badge .label,
            body.print-thermal .invoice-badge .number {
                font-size: 12px;
                display: inline;
                margin: 0;
            }
            body.print-thermal .invoice-body {
                padding: 2mm 2mm 0;
            }
            body.print-thermal .meta-row {
                flex-direction: column;
                gap: 0;
                border-bottom: 1px dashed #000;
                padding-bottom: 1mm;
                margin-bottom: 2mm;
            }
            body.print-thermal .meta-box {
                flex: none;
                min-width: auto;
                display: flex;
                justify-content: space-between;
                font-size: 10px;
                margin: 0;
                line-height: 1.3;
            }
            body.print-thermal .meta-box h3 {
                font-size: 10px;
                border: none;
                margin: 0;
                padding: 0;
                display: inline;
                font-weight: bold;
            }
            body.print-thermal .meta-box p {
                font-size: 10px;
                display: inline;
                margin: 0;
                line-height: 1.3;
            }
            /* Table -> receipt style */
            body.print-thermal .items-table {
                border-collapse: collapse;
                width: 100%;
                margin: 2mm 0;
            }
            body.print-thermal .items-table thead {
                display: none;
            }
            body.print-thermal .items-table tbody td {
                display: block;
                text-align: right;
                padding: 0.5mm 0;
                font-size: 10px;
                border-bottom: none;
                margin: 0;
            }
            body.print-thermal .items-table tbody td::before {
                content: attr(data-label) ": ";
                float: left;
                font-weight: bold;
            }
            body.print-thermal .items-table tbody tr {
                border-bottom: 1px dotted #aaa;
                display: block;
                padding: 1mm 0;
                margin: 0;
            }
            /* Totals */
            body.print-thermal .totals-section {
                justify-content: flex-start;
                margin-top: 2mm;
            }
            body.print-thermal .totals-grid {
                width: 100%;
                font-size: 10px;
            }
            body.print-thermal .totals-grid .row {
                padding: 0.5mm 0;
            }
            body.print-thermal .totals-grid .row.total {
                font-size: 11px;
                border-top: 1px solid #000;
                padding-top: 1mm;
                margin-top: 1mm;
            }
            /* Hide exchange policy & footer in thermal */
            body.print-thermal .exchange-policy,
            body.print-thermal .footer {
                display: none;
            }
            /* Page margins reset to zero for minimal top space */
            @page {
                size: 80mm auto;
                margin: 0;
            }
        }
    </style>
</head>
<body>
<div class="invoice">
    <div class="invoice-header">
           <div class="company-info">
            <h1><?php echo htmlspecialchars($tx); ?></h1>
            <div class="address">
                Shop No 82<br>
                📞 03212121294 | 03362121292
            </div>
        </div>
        <div class="invoice-badge">
            <div class="label">Invoice</div>
            <div class="number">#<?php echo $orderId; ?></div>
        </div>
    </div>

    <div class="invoice-body">
        <!-- Meta Information -->
        <div class="meta-row">
            <div class="meta-box">
                <h3>Date & Time</h3>
                <p><?php echo date('d M, Y  h:i A', strtotime($dateTime)); ?></p>
            </div>
            <div class="meta-box">
                <h3>Cashier</h3>
                <p><?php echo htmlspecialchars($loginUser); ?> (<?php echo htmlspecialchars($userRole); ?>)</p>
            </div>
            <div class="meta-box">
                <h3>Customer</h3>
                <p>
                    <?php if($customerName && $customerName != 'walkin'): ?>
                        <?php echo htmlspecialchars($customerName); ?><br>
                        <small><?php echo $customerPhone; ?></small>
                    <?php else: ?>
                        Walk‑in Customer
                    <?php endif; ?>
                </p>
            </div>
            <div class="meta-box">
                <h3>Payment Method</h3>
                <p>
                    <?php 
                        $icons = ['cash'=>'💵','credit'=>'💳','bank1'=>'🏦','bank2'=>'🏦','bank3'=>'🏦'];
                        echo ($icons[$paidBy] ?? '💵') . ' ' . ucfirst($paidBy);
                    ?>
                </p>
            </div>
        </div>

        <!-- Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Item</th>
                    <th>Unit</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Disc %</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <?php $sr = 1; ?>
                <?php foreach ($orderDetails as $item): ?>
                <tr>
                    <td data-label="#"><?php echo $sr++; ?></td>
                    <td data-label="Item" class="item-name"><?php echo htmlspecialchars($item['product_name']); ?></td>
                    <td data-label="unit" class="item-name"><?php echo htmlspecialchars($item['product_unit']); ?></td>
                    <td data-label="Qty"><?php echo $item['product_quantity']; ?></td>
                    <td data-label="Price">Rs. <?php echo number_format(floatval($item['product_price']), 2); ?></td>
                    <td data-label="Disc %"><?php echo floatval($item['discount']); ?>%</td>
                    <td data-label="Total">Rs. <?php echo number_format(floatval($item['net_amount']), 2); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Totals -->
        <?php
            $subTotal = 0;
            foreach ($orderDetails as $item) {
                $subTotal += floatval($item['product_total']);
            }
            $tax = floatval($taxAmount);
        ?>
        <div class="totals-section">
            <div class="totals-grid">
                <div class="row">
                    <span>Subtotal</span>
                    <span>Rs. <?php echo number_format($subTotal, 2); ?></span>
                </div>
                <?php if($discounted > 0): ?>
                <div class="row discount">
                    <span>Discount</span>
                    <span>‑ Rs. <?php echo number_format($discounted, 2); ?></span>
                </div>
                <?php endif; ?>
                <?php if($tax > 0): ?>
                <div class="row">
                    <span>Tax (<?php echo $discountPer ?? '0'; ?>%)</span>
                    <span>Rs. <?php echo number_format($tax, 2); ?></span>
                </div>
                <?php endif; ?>
                <div class="row">
                    <span>Total Amount</span>
                    <span>Rs. <?php echo number_format($discountedAmount, 2); ?></span>
                </div>
                <div class="row">
                    <span>Cutting</span>
                    <span>Rs. <?php echo number_format($cutting, 2); ?></span>
                </div>
                <div class="row">
                    <span>Loading</span>
                    <span>Rs. <?php echo number_format($loading, 2); ?></span>
                </div>
                <div class="row">
                    <span>Vehicle Rent</span>
                    <span>Rs. <?php echo number_format($vehicle_rent, 2); ?></span>
                </div>
                <div class="row">
                    <span>CTN</span>
                    <span>Rs. <?php echo number_format($ctn, 2); ?></span>
                </div>
                <div class="row">
                    <span>Bora</span>
                    <span>Rs. <?php echo number_format($bora, 2); ?></span>
                </div>
                
                <?php if($pre > 0): ?>
                <div class="row">
                    <span>Previous Due</span>
                    <span>Rs. <?php echo number_format($pre, 2); ?></span>
                </div>
                <?php endif; ?>
                <div class="row total">
                    <span>Grand Total</span>
                    <span>Rs. <?php echo number_format($close, 2); ?></span>
                </div>
                <?php if($paidBy == 'cash' && $cashAmount > 0): ?>
                <div class="row payment">
                    <span>Cash Received</span>
                    <span>Rs. <?php echo number_format($cashAmount, 2); ?></span>
                </div>
                <div class="row payment">
                    <span>Change</span>
                    <span>Rs. <?php echo number_format(abs($changeAmount), 2); ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Exchange Policy -->
        <div class="exchange-policy">
            <strong>📋 Exchange Policy</strong>
            1. Exchanges accepted within 7 days of purchase.<br>
            2. Items must be in original condition with all tags attached.<br>
            3. This invoice must be presented at the time of exchange.
        </div>

        <!-- Footer -->
        <div class="footer">
            Thank you for your purchase!<br>
            This is a computer‑generated invoice and does not require a physical signature.
        </div>
    </div>

    <!-- Action Buttons (hidden when printing) -->
    <div class="button-group no-print">
        <button class="btn btn-primary" id="printTrigger">
            🖨️ Print Invoice
        </button>
        <form method="post" style="display:inline;">
            <button type="submit" name="exit" class="btn btn-secondary">
                ↩️ Exit & Return to POS
            </button>
        </form>
    </div>
</div>

<!-- Print options modal -->
<div id="printModal" class="modal no-print">
    <div class="modal-dialog">
        <h2>Select Print Type</h2>
        <p>Choose your printer format:</p>
        <div class="modal-buttons">
            <button class="modal-btn thermal" onclick="selectPrint('thermal')">🖨️ Thermal Receipt (80mm)</button>
            <button class="modal-btn a4" onclick="selectPrint('a4')">📄 A4 / A5 Sheet</button>
        </div>
        <button class="modal-close" onclick="closeModal()">Cancel</button>
    </div>
</div>

<script>
    // Show modal on print trigger click
    document.getElementById('printTrigger').addEventListener('click', function(e) {
        e.preventDefault();
        document.getElementById('printModal').classList.add('active');
    });

    function closeModal() {
        document.getElementById('printModal').classList.remove('active');
    }

    function selectPrint(type) {
        if (type === 'thermal') {
            document.body.classList.add('print-thermal');
        } else {
            document.body.classList.remove('print-thermal');
        }
        document.getElementById('printModal').classList.remove('active');
        window.print();
    }

    // Clean up class after print dialog closes
    window.addEventListener('afterprint', function() {
        document.body.classList.remove('print-thermal');
    });

    // Ctrl+P shortcut (still shows modal)
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            document.getElementById('printModal').classList.add('active');
        }
    });
</script>

    <link rel="stylesheet" href="../css/responsive-mobile.css">
    <script src="../js/responsive-mobile.js"></script>
</body>
</html>