<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$sale_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$is_thermal = isset($_GET['print']) && $_GET['print'] == 'thermal';

$sale_sql = "SELECT ls.*, c.name as customer_name, c.phone as customer_phone, c.vehicle_no 
             FROM lube_sales ls
             LEFT JOIN customers c ON ls.customer_id = c.id
             WHERE ls.id = $sale_id";
$sale_result = mysqli_query($conn, $sale_sql);
$sale = mysqli_fetch_assoc($sale_result);

if(!$sale) {
    header("Location: lube_sales.php");
    exit();
}

$items_sql = "SELECT lsi.*, lp.product_name, lp.product_code 
              FROM lube_sale_items lsi
              JOIN lube_products lp ON lsi.product_id = lp.id
              WHERE lsi.sale_id = $sale_id";
$items_result = mysqli_query($conn, $items_sql);

if($is_thermal):
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thermal Invoice #<?php echo $sale['sale_invoice']; ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            width: 80mm;
            margin: 0 auto;
            padding: 5px;
            background: white;
        }
        .invoice-box {
            max-width: 80mm;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            border-bottom: 1px dashed #000;
            padding-bottom: 8px;
            margin-bottom: 8px;
        }
        .logo {
            max-width: 60px;
            margin-bottom: 5px;
        }
        .shop-name {
            font-size: 16px;
            font-weight: bold;
            margin: 5px 0;
        }
        .shop-address {
            font-size: 10px;
            margin: 3px 0;
        }
        .invoice-title {
            text-align: center;
            font-weight: bold;
            font-size: 14px;
            margin: 10px 0;
            text-decoration: underline;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 11px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
        }
        .items-table th, .items-table td {
            border-bottom: 1px dotted #ccc;
            padding: 5px 2px;
            text-align: left;
            font-size: 11px;
        }
        .items-table th {
            border-bottom: 1px solid #000;
            font-weight: bold;
        }
        .text-right {
            text-align: right;
        }
        .text-center {
            text-align: center;
        }
        .total-row {
            margin-top: 8px;
            border-top: 1px dashed #000;
            padding-top: 5px;
        }
        .total-line {
            display: flex;
            justify-content: space-between;
            margin: 4px 0;
            font-weight: bold;
        }
        .grand-total {
            font-size: 14px;
            font-weight: bold;
            border-top: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 5px 0;
            margin: 5px 0;
        }
        .footer {
            text-align: center;
            margin-top: 15px;
            padding-top: 8px;
            border-top: 1px dashed #000;
            font-size: 10px;
        }
        .thankyou {
            font-size: 12px;
            font-weight: bold;
            margin: 10px 0;
            text-align: center;
        }
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none;
            }
        }
    </style>
</head>
<body onload="window.print();">
<div class="invoice-box">
    <div class="header">
        <img src="../assets/images/logo.jpeg" class="logo" alt="Logo" onerror="this.style.display='none'">
        <div class="shop-name">ALFATEH PETROLEUM SERVICE</div>
        <div class="shop-address">Complete Fuel Station Management Solution</div>
        <div class="shop-address">Shaikh Bhirkyo Road Tando Muhammad Khan</div>
    </div>
    
    <div class="invoice-title">LUBE SALE INVOICE</div>
    
    <div class="info-row">
        <span>Invoice No:</span>
        <span><strong><?php echo $sale['sale_invoice']; ?></strong></span>
    </div>
    <div class="info-row">
        <span>Date:</span>
        <span><?php echo date('d-m-Y h:i A', strtotime($sale['sale_date'])); ?></span>
    </div>
    <div class="info-row">
        <span>Payment:</span>
        <span><?php echo ucfirst($sale['payment_method']); ?></span>
    </div>
    <?php if($sale['customer_type'] == 'credit_customer' && $sale['customer_name']): ?>
    <div class="info-row">
        <span>Customer:</span>
        <span><?php echo htmlspecialchars($sale['customer_name']); ?></span>
    </div>
    <div class="info-row">
        <span>Phone:</span>
        <span><?php echo htmlspecialchars($sale['customer_phone'] ?: '-'); ?></span>
    </div>
    <?php endif; ?>
    
    <table class="items-table">
        <thead>
            <tr>
                <th>Item</th>
                <th class="text-right">Qty</th>
                <th class="text-right">Price</th>
                <th class="text-right">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $sr_no = 1;
            mysqli_data_seek($items_result, 0);
            while($item = mysqli_fetch_assoc($items_result)): 
            ?>
            <tr>
                <td><?php echo $sr_no++; ?>. <?php echo htmlspecialchars($item['product_name']); ?></div>
                <td class="text-right"><?php echo number_format($item['quantity'], 2); ?></div>
                <td class="text-right"><?php echo number_format($item['sale_price'], 2); ?></div>
                <td class="text-right"><?php echo number_format($item['total'], 2); ?></div>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
    
    <div class="total-row">
        <div class="total-line">
            <span>Subtotal:</span>
            <span>Rs <?php echo number_format($sale['subtotal'], 2); ?></span>
        </div>
        <?php if($sale['discount'] > 0): ?>
        <div class="total-line">
            <span>Discount:</span>
            <span>- Rs <?php echo number_format($sale['discount'], 2); ?></span>
        </div>
        <?php endif; ?>
        <?php if($sale['advance_used'] > 0): ?>
        <div class="total-line">
            <span>Advance Used:</span>
            <span>- Rs <?php echo number_format($sale['advance_used'], 2); ?></span>
        </div>
        <?php endif; ?>
        <div class="grand-total">
            <span>TOTAL:</span>
            <span>Rs <?php echo number_format($sale['total_amount'], 2); ?></span>
        </div>
        <?php if($sale['cash_received'] > 0): ?>
        <div class="total-line">
            <span>Cash Received:</span>
            <span>Rs <?php echo number_format($sale['cash_received'], 2); ?></span>
        </div>
        <div class="total-line">
            <span>Change:</span>
            <span>Rs <?php echo number_format($sale['cash_received'] - $sale['total_amount'], 2); ?></span>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="thankyou">
        Thank you for your purchase!
    </div>
    
    <div class="footer">
        <div>Powered by ALFATEH Petroleum</div>
        <div><?php echo date('d-m-Y h:i A'); ?></div>
        <div>** This is a computer generated invoice **</div>
    </div>
</div>
<div class="no-print" style="text-align: center; margin-top: 10px;">
    <button onclick="window.print()" style="padding: 5px 15px; margin: 0 5px;">Print</button>
    <button onclick="window.location.href='lube_sales.php'" style="padding: 5px 15px; margin: 0 5px;">Close & Back</button>
</div>

<script>
    // Auto print
    window.print();
    
    // After print, stay on page or redirect
    window.onafterprint = function() {
        // Optional: auto redirect after print
        // window.location.href = 'lube_sales.php';
    }
</script>
</body>
</html>
<?php else: ?>
<!-- Regular Web View -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lube Sale Invoice #<?php echo $sale['sale_invoice']; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        * {
            font-family: 'Poppins', sans-serif;
        }
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Quicksand', sans-serif;
        }
        .invoice-container {
            max-width: 800px;
            margin: 30px auto;
            background: #fff;
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .invoice-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            padding: 25px 30px;
            text-align: center;
        }
        .invoice-header h1 {
            margin: 0;
            font-size: 24px;
        }
        .invoice-body {
            padding: 30px;
        }
        .company-info {
            text-align: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        .company-info h3 {
            margin: 0;
            color: #A04657;
        }
        .invoice-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            padding: 15px;
            background: #f8f9fc;
            border-radius: 12px;
        }
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .invoice-table th {
            background: #f8f9fc;
            padding: 12px;
            font-size: 12px;
            font-weight: 700;
            text-align: left;
            border-bottom: 2px solid #e8e8e8;
        }
        .invoice-table td {
            padding: 10px 12px;
            border-bottom: 1px solid #f0f0f0;
            font-size: 13px;
        }
        .totals-section {
            background: #f8f9fc;
            border-radius: 12px;
            padding: 15px;
            margin-top: 20px;
        }
        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
        }
        .grand-total {
            font-size: 18px;
            font-weight: 800;
            color: #A04657;
            border-top: 2px solid #e8e8e8;
            padding-top: 10px;
            margin-top: 5px;
        }
        .footer {
            background: #f8f9fc;
            padding: 20px;
            text-align: center;
            font-size: 11px;
            color: #999;
        }
        .btn-print {
            display: inline-block;
            width: auto;
            margin: 0 10px;
            padding: 12px 24px;
            background: #A04657;
            color: #fff;
            border: none;
            border-radius: 40px;
            font-weight: 600;
            cursor: pointer;
            text-align: center;
            text-decoration: none;
        }
        .btn-print:hover {
            background: #6b2a36;
        }
        .btn-back {
            background: #6c757d;
        }
        .btn-back:hover {
            background: #5a6268;
        }
        .btn-thermal {
            background: #17a2b8;
        }
        .btn-thermal:hover {
            background: #138496;
        }
        .button-group {
            text-align: center;
            margin: 20px 0;
        }
        @media print {
            .button-group, .no-print {
                display: none !important;
            }
            .invoice-container {
                box-shadow: none;
                margin: 0;
            }
        }
    </style>
</head>
<body>
<div class="invoice-container">
    <div class="invoice-header">
        <h1><i class="fas fa-gas-pump"></i> ALFATEH PETROLEUM SERVICE</h1>
        <p>Complete Fuel Station Management Solution</p>
    </div>
    
    <div class="invoice-body">
        <div class="company-info">
            <h3>LUBRICANT SALE INVOICE</h3>
        </div>
        
        <div class="invoice-details">
            <div>
                <strong>Invoice No:</strong> <?php echo $sale['sale_invoice']; ?><br>
                <strong>Date:</strong> <?php echo date('d-m-Y', strtotime($sale['sale_date'])); ?><br>
                <strong>Time:</strong> <?php echo date('h:i A', strtotime($sale['created_at'])); ?>
            </div>
            <div>
                <?php if($sale['customer_type'] == 'credit_customer' && $sale['customer_name']): ?>
                    <strong>Customer:</strong> <?php echo htmlspecialchars($sale['customer_name']); ?><br>
                    <strong>Phone:</strong> <?php echo htmlspecialchars($sale['customer_phone'] ?: '-'); ?><br>
                    <strong>Vehicle:</strong> <?php echo htmlspecialchars($sale['vehicle_no'] ?: '-'); ?>
                <?php else: ?>
                    <strong>Customer Type:</strong> Walk-in Customer<br>
                    <strong>Payment:</strong> <?php echo ucfirst($sale['payment_method']); ?>
                <?php endif; ?>
            </div>
        </div>
        
        <table class="invoice-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Price (Rs)</th>
                    <th>Total (Rs)</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                mysqli_data_seek($items_result, 0);
                $sr_no = 1;
                while($item = mysqli_fetch_assoc($items_result)): 
                ?>
                <tr>
                    <td><?php echo $sr_no++; ?></div>
                    <td><?php echo htmlspecialchars($item['product_name']); ?><br><small><?php echo $item['product_code']; ?></small></div>
                    <td><?php echo number_format($item['quantity'], 2); ?></div>
                    <td>Rs <?php echo number_format($item['sale_price'], 2); ?></div>
                    <td>Rs <?php echo number_format($item['total'], 2); ?></div>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
        
        <div class="totals-section">
            <div class="total-row">
                <span>Subtotal:</span>
                <strong>Rs <?php echo number_format($sale['subtotal'], 2); ?></strong>
            </div>
            <?php if($sale['discount'] > 0): ?>
            <div class="total-row">
                <span>Discount:</span>
                <strong>- Rs <?php echo number_format($sale['discount'], 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($sale['advance_used'] > 0): ?>
            <div class="total-row">
                <span>Advance Used:</span>
                <strong>- Rs <?php echo number_format($sale['advance_used'], 2); ?></strong>
            </div>
            <?php endif; ?>
            <div class="total-row grand-total">
                <span>Grand Total:</span>
                <strong>Rs <?php echo number_format($sale['total_amount'], 2); ?></strong>
            </div>
            <?php if($sale['customer_type'] == 'walkin' && $sale['cash_received'] > 0): ?>
            <div class="total-row">
                <span>Cash Received:</span>
                <strong>Rs <?php echo number_format($sale['cash_received'], 2); ?></strong>
            </div>
            <div class="total-row">
                <span>Change Due:</span>
                <strong>Rs <?php echo number_format($sale['cash_received'] - $sale['total_amount'], 2); ?></strong>
            </div>
            <?php endif; ?>
        </div>
        
        <div style="margin-top: 20px; text-align: center; font-size: 12px; color: #666;">
            <i class="fas fa-check-circle" style="color: #28a745;"></i> Thank you for your purchase!
        </div>
    </div>
    
    <div class="footer">
        <p><?php echo htmlspecialchars($sale['created_by']); ?> | Generated on <?php echo date('d-m-Y h:i A'); ?></p>
        <p>This is a computer generated invoice - No signature required</p>
    </div>
</div>

<div class="button-group no-print">
    <button onclick="window.print()" class="btn-print">
        <i class="fas fa-print"></i> Print Invoice
    </button>
    <a href="lube_sales.php" class="btn-print btn-back">
        <i class="fas fa-arrow-left"></i> Back to Sales
    </a>
    <button onclick="window.location.href='lube_sale_invoice.php?id=<?php echo $sale_id; ?>&print=thermal'" class="btn-print btn-thermal">
        <i class="fas fa-receipt"></i> Thermal Print
    </button>
</div>

<script>
    // Function to close window (works if opened via JavaScript)
    function closeWindow() {
        if (window.opener && !window.opener.closed) {
            window.close();
        } else {
            window.location.href = 'lube_sales.php';
        }
    }
</script>
</body>
</html>
<?php endif; ?>