<?php
session_start();
require_once '../../assets/db_connect.php';

if (!isset($_SESSION['user']['id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

$product_id = $_GET['product_id'] ?? 0;
$product_id = intval($product_id);
$shop_id = $_SESSION['user']['shop_id'];

// Get product details - Use product selling_price
$sql = "SELECT 
            p.*,
            COALESCE(ps.total_qty, 0) as current_stock
        FROM products p
        LEFT JOIN product_stock_view ps ON p.id = ps.product_id
        WHERE p.id = ? AND p.shop_id = ?
        LIMIT 1";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    echo '<div class="alert alert-danger">Product not found</div>';
    exit();
}

// Get available batches for stock tracking (ONLY batches with positive stock)
$batches_sql = "SELECT 
                    pb.id, 
                    pb.batch_no, 
                    pb.sell_price as batch_price,
                    pb.expiry_date,
                    DATEDIFF(pb.expiry_date, CURDATE()) as days_left,
                    COALESCE(SUM(
                        CASE 
                            WHEN im.movement_type IN ('PURCHASE', 'RETURN') THEN im.change_qty
                            WHEN im.movement_type IN ('SALE', 'ADJUSTMENT') THEN -im.change_qty
                            ELSE 0
                        END
                    ), 0) as current_qty
                FROM product_batches pb
                LEFT JOIN inventory_movements im ON pb.id = im.batch_id
                WHERE pb.product_id = ? 
                AND pb.shop_id = ?
                AND pb.is_active = 1
                GROUP BY pb.id, pb.batch_no, pb.sell_price, pb.expiry_date
                HAVING current_qty > 0
                ORDER BY pb.expiry_date ASC";
                
$batches_stmt = $pdo->prepare($batches_sql);
$batches_stmt->execute([$product_id, $shop_id]);
$batches = $batches_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get default batch for auto-selection (FIFO - only from batches with stock)
$default_batch_sql = "SELECT 
                        pb.id,
                        pb.batch_no
                      FROM product_batches pb
                      WHERE pb.product_id = ? 
                      AND pb.shop_id = ?
                      AND pb.is_active = 1
                      AND (
                          SELECT COALESCE(SUM(
                              CASE 
                                  WHEN im.movement_type IN ('PURCHASE', 'RETURN') THEN im.change_qty
                                  WHEN im.movement_type IN ('SALE', 'ADJUSTMENT') THEN -im.change_qty
                                  ELSE 0
                              END
                          ), 0) 
                          FROM inventory_movements im 
                          WHERE im.batch_id = pb.id
                      ) > 0
                      ORDER BY pb.expiry_date ASC 
                      LIMIT 1";
                      
$default_batch_stmt = $pdo->prepare($default_batch_sql);
$default_batch_stmt->execute([$product_id, $shop_id]);
$default_batch = $default_batch_stmt->fetch(PDO::FETCH_ASSOC);

// Generate invoice number
$invoice_no = 'SALE-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);

// Use product's selling price (NOT batch price)
$selling_price = $product['selling_price'];
?>

<div class="container-fluid p-0">
    <div class="card border-0">
        <div class="card-header bg-primary text-white">
            <h4 class="mb-0"><i class="fas fa-cash-register"></i> Sell Product</h4>
        </div>
        <div class="card-body">
            <!-- Product Info -->
            <div class="alert alert-info">
                <div class="row">
                    <div class="col-md-3">
                        <strong>Product:</strong> <?= htmlspecialchars($product['name']) ?>
                    </div>
                    <div class="col-md-3">
                        <strong>Available Stock:</strong> 
                        <span class="badge <?= $product['current_stock'] <= 20 ? 'badge-warning' : 'badge-success' ?>">
                            <?= $product['current_stock'] ?>
                        </span>
                    </div>
                    <div class="col-md-3">
                        <strong>Selling Price:</strong> 
                        <span class="text-success font-weight-bold">
                            <?= number_format($selling_price, 2) ?>
                        </span>
                        <br><small class="text-muted">Fixed product price</small>
                    </div>
                    <div class="col-md-3">
                        <strong>VAT:</strong> <?= $product['vat_percent'] ?>%
                    </div>
                </div>
            </div>
            
            <!-- POS Form -->
            <form id="posForm">
                <input type="hidden" name="product_id" value="<?= $product_id ?>">
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
                <input type="hidden" name="created_by" value="<?= $_SESSION['user']['id'] ?>">
                <input type="hidden" name="vat_percent" value="<?= $product['vat_percent'] ?>">
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Invoice Number</label>
                            <input type="text" name="invoice_no" class="form-control" value="<?= $invoice_no ?>" readonly>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Sale Date & Time</label>
                            <input type="datetime-local" name="sale_date" class="form-control" 
                                   value="<?= date('Y-m-d\TH:i') ?>" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Customer Name</label>
                            <input type="text" name="customer_name" class="form-control" 
                                   placeholder="Enter customer name or leave empty for walk-in">
                            <small class="text-muted">Type customer name or leave blank for walk-in</small>
                        </div>
                    </div>
                </div>
                
                <!-- Sale Details -->
                <div class="card mt-3">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-shopping-cart"></i> Sale Details</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Quantity *</label>
                                    <input type="number" name="qty" class="form-control" min="1" 
                                           max="<?= $product['current_stock'] ?>" value="1" required>
                                    <small class="text-muted">Max: <?= $product['current_stock'] ?> available</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Unit Price *</label>
                                    <input type="number" name="unit_price" class="form-control" step="0.01" min="0.01" 
                                           value="<?= $selling_price ?>" required readonly>
                                    <small class="text-muted">Fixed product selling price</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Batch Selection</label>
                                    <select name="batch_id" class="form-control">
                                        <option value="">Auto-select (FIFO - First Expiry)</option>
                                        <?php foreach($batches as $batch): ?>
                                        <option value="<?= $batch['id'] ?>" 
                                                data-qty="<?= $batch['current_qty'] ?>"
                                                <?= $default_batch && $default_batch['id'] == $batch['id'] ? 'selected' : '' ?>>
                                            <?= $batch['batch_no'] ?> 
                                            (<?= $batch['current_qty'] ?> left, 
                                            Exp: <?= date('M d, Y', strtotime($batch['expiry_date'])) ?>)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="text-muted">For stock tracking only - price remains fixed</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Discount (%)</label>
                                    <div class="input-group">
                                        <input type="number" name="discount" class="form-control" step="0.01" min="0" max="100" value="0">
                                        <div class="input-group-append">
                                            <span class="input-group-text">%</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Stock Availability Warning -->
                        <?php if($product['current_stock'] <= 0): ?>
                        <div class="alert alert-danger mt-3">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>Out of Stock!</strong> This product has no available stock.
                        </div>
                        <?php elseif($product['current_stock'] <= 20): ?>
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-circle"></i>
                            <strong>Low Stock Warning:</strong> Only <?= $product['current_stock'] ?> units available.
                        </div>
                        <?php endif; ?>
                        
                        <!-- Batch Information -->
                        <?php if(!empty($batches)): ?>
                        <div class="alert alert-secondary mt-3">
                            <h6><i class="fas fa-boxes"></i> Available Batches (Stock Tracking):</h6>
                            <div class="row">
                                <?php foreach($batches as $batch): ?>
                                <div class="col-md-3 mb-2">
                                    <div class="card <?= $default_batch && $default_batch['id'] == $batch['id'] ? 'border-primary' : 'border-light' ?>">
                                        <div class="card-body p-2">
                                            <small>
                                                <strong><?= $batch['batch_no'] ?></strong>
                                                <?php if($default_batch && $default_batch['id'] == $batch['id']): ?>
                                                <span class="badge badge-primary float-right">Default</span>
                                                <?php endif; ?>
                                                <br>
                                                Stock: <?= $batch['current_qty'] ?><br>
                                                Expiry: <?= $batch['days_left'] ?> days left
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <small class="text-muted mt-2">
                                <i class="fas fa-info-circle"></i> 
                                Batch selection affects stock management only. Selling price is fixed at <?= number_format($selling_price, 2) ?>.
                            </small>
                        </div>
                        <?php else: ?>
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-box-open"></i>
                            No active batches with stock available. Please add stock first.
                        </div>
                        <?php endif; ?>
                        
                        <!-- Fixed Price Notice -->
                        <div class="alert alert-success mt-3">
                            <div class="row">
                                <div class="col-md-12">
                                    <h6><i class="fas fa-lock"></i> Fixed Pricing Policy</h6>
                                    <p class="mb-1">
                                        <strong>Selling Price:</strong> 
                                        <span class="font-weight-bold"><?= number_format($selling_price, 2) ?></span>
                                    </p>
                                    <p class="mb-0">
                                        <small>
                                            <i class="fas fa-info-circle"></i> 
                                            This product uses a fixed selling price. The price does not change based on batch purchase cost.
                                        </small>
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Calculated Totals -->
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <div class="alert alert-success">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <strong>Subtotal:</strong> TZS <span id="subtotal">0.00</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Discount:</strong> TZS <span id="discountAmount">0.00</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>VAT (<?= $product['vat_percent'] ?>%):</strong> TZS <span id="vatAmount">0.00</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Total:</strong> TZS <span id="saleTotal">0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Payment -->
                <div class="card mt-3">
                    <div class="card-header bg-light">
                        <h5 class="mb-0"><i class="fas fa-credit-card"></i> Payment</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Payment Method *</label>
                                    <select name="payment_method" class="form-control" required>
                                        <option value="CASH">Cash</option>
                                        <option value="M-PESA">M-PESA</option>
                                        <option value="TIGO-PESA">Tigo Pesa</option>
                                        <option value="AIRTEL-MONEY">Airtel Money</option>
                                        <option value="CARD">Credit/Debit Card</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Amount Paid *</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">TZS</span>
                                        </div>
                                        <input type="number" name="amount_paid" class="form-control" step="0.01" min="0.01" required>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Change</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">TZS</span>
                                        </div>
                                        <input type="text" id="changeAmount" class="form-control" readonly value="0.00">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Summary -->
                        <div class="row mt-3">
                            <div class="col-md-12">
                                <div class="card bg-light">
                                    <div class="card-body p-3">
                                        <div class="row text-center">
                                            <div class="col-md-4">
                                                <small class="text-muted">Unit Price</small><br>
                                                <strong class="text-success"><?= number_format($selling_price, 2) ?></strong>
                                            </div>
                                            <div class="col-md-4">
                                                <small class="text-muted">VAT Rate</small><br>
                                                <strong><?= $product['vat_percent'] ?>%</strong>
                                            </div>
                                            <div class="col-md-4">
                                                <small class="text-muted">Payment Due</small><br>
                                                <strong class="text-primary" id="paymentDue">0.00</strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Form Actions -->
                <div class="row mt-4">
                    <div class="col-md-12">
                        <div class="d-flex justify-content-between">
                            <button type="button" class="btn btn-secondary" onclick="Swal.close()">
                                <i class="fas fa-times"></i> Cancel
                            </button>
                            <button type="submit" class="btn btn-primary btn-lg" <?= $product['current_stock'] <= 0 ? 'disabled' : '' ?>>
                                <i class="fas fa-check"></i> Complete Sale
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Calculate totals
    function calculateTotals() {
        const qty = parseInt($('input[name="qty"]').val()) || 0;
        const price = parseFloat($('input[name="unit_price"]').val()) || 0;
        const discount = parseFloat($('input[name="discount"]').val()) || 0;
        const vatPercent = <?= $product['vat_percent'] ?>;
        
        const subtotal = qty * price;
        const discountAmount = subtotal * (discount / 100);
        const afterDiscount = subtotal - discountAmount;
        const vatAmount = afterDiscount * (vatPercent / 100);
        const total = afterDiscount + vatAmount;
        
        $('#subtotal').text(subtotal.toFixed(2));
        $('#discountAmount').text(discountAmount.toFixed(2));
        $('#vatAmount').text(vatAmount.toFixed(2));
        $('#saleTotal').text(total.toFixed(2));
        $('#paymentDue').text(total.toFixed(2));
        
        // Calculate change
        const amountPaid = parseFloat($('input[name="amount_paid"]').val()) || 0;
        const change = amountPaid - total;
        $('#changeAmount').val(change > 0 ? change.toFixed(2) : '0.00');
        
        return total;
    }
    
    // Update totals when inputs change
    $('input[name="qty"], input[name="discount"], input[name="amount_paid"]').on('input', calculateTotals);
    
    // Update batch quantity restrictions when batch is selected
    $('select[name="batch_id"]').change(function() {
        const selectedOption = $(this).find('option:selected');
        const batchQty = selectedOption.data('qty');
        
        if (batchQty) {
            const maxQty = Math.min(batchQty, <?= $product['current_stock'] ?>);
            $('input[name="qty"]').attr('max', maxQty);
            $('input[name="qty"]').next('small').text('Max: ' + maxQty + ' available (from selected batch)');
        } else {
            $('input[name="qty"]').attr('max', <?= $product['current_stock'] ?>);
            $('input[name="qty"]').next('small').text('Max: <?= $product['current_stock'] ?> available (total stock)');
        }
    });
    
    // Auto-fill amount paid with total
    $('#saleTotal').on('DOMSubtreeModified', function() {
        const total = parseFloat($(this).text()) || 0;
        if (total > 0) {
            $('input[name="amount_paid"]').val(total.toFixed(2));
            calculateTotals();
        }
    });
    
    // Trigger initial calculation
    calculateTotals();
    
    // Show warning if trying to change price (since it's readonly)
    $('input[name="unit_price"]').on('click', function() {
        Swal.fire({
            title: 'Fixed Price',
            text: 'This product uses a fixed selling price. To change the price, edit the product details.',
            icon: 'info',
            confirmButtonText: 'OK'
        });
    });
});
</script>