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

// Ensure user + shop
if (!isset($_SESSION['user']['shop_id']) || !isset($_SESSION['user']['id'])) {
    echo "<div class='col-md-10 ml-sm-auto px-4 py-4'>
            <div class='alert alert-danger'>
                <i class='fas fa-exclamation-triangle'></i> Shop information missing. Please contact admin.
            </div>
          </div>";
    require_once '../includes/footer.php';
    exit;
}

$shop_id = (int)$_SESSION['user']['shop_id'];
$user_id = (int)$_SESSION['user']['id'];
$shop_name = $_SESSION['user']['shop_name'] ?? 'Your Shop';

// Get existing customers for dropdown
$customers = $pdo->query("SELECT id, name, phone FROM customers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-primary">
            <i class="fas fa-cash-register"></i> New Sale
        </h3>
        <div>
            <span class="badge badge-info">Shop: <?= htmlspecialchars($shop_name) ?></span>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertPlaceholder"></div>

    <form id="saleForm" autocomplete="off">
        <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
        <input type="hidden" name="created_by" value="<?= $user_id ?>">

        <!-- Customer & Basic Info -->
        <div class="card mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-user"></i> Customer Information</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Select Customer (Optional)</label>
                            <select class="form-control" name="customer_id" id="customerSelect">
                                <option value="">-- Walk-in Customer --</option>
                                <?php foreach ($customers as $customer): ?>
                                    <option value="<?= $customer['id'] ?>">
                                        <?= htmlspecialchars($customer['name']) ?>
                                        <?php if ($customer['phone']): ?> - <?= htmlspecialchars($customer['phone']) ?><?php endif; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">New Customer Name</label>
                            <input type="text" class="form-control" name="new_customer_name" 
                                   placeholder="Enter customer name (if new)">
                            <small class="form-text text-muted">Leave blank if customer already exists</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Search -->
        <div class="card mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-search"></i> Add Product</h5>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <input type="text" id="productSearch" class="form-control" 
                           placeholder="Search by product name or SKU...">
                    <div id="productResults" class="list-group mt-1" 
                         style="display:none; max-height:200px; overflow:auto; position:absolute; z-index:1000; width:100%;"></div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Product</label>
                            <input type="text" id="selectedProductName" class="form-control" readonly>
                            <input type="hidden" id="selectedProductId">
                            <small class="form-text text-muted" id="productSku"></small>
                        </div>
                    </div>
                    
                    <div class="col-md-3">
                        <div class="form-group">
                            <label class="font-weight-bold">Batch</label>
                            <select class="form-control" id="batchSelect" disabled>
                                <option value="">Select Batch</option>
                            </select>
                            <input type="hidden" id="batchId">
                        </div>
                    </div>
                    
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Price (TSh)</label>
                            <input type="text" id="unitPrice" class="form-control" readonly>
                        </div>
                    </div>
                    
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Available</label>
                            <input type="text" id="qtyAvailable" class="form-control" readonly>
                        </div>
                    </div>
                    
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Expiry</label>
                            <input type="text" id="expiryDate" class="form-control" readonly>
                        </div>
                    </div>
                </div>

                <div class="row mt-2">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Quantity</label>
                            <input type="number" id="qty" class="form-control" min="1" value="1" step="1">
                        </div>
                    </div>
                    
                    <div class="col-md-2">
                        <div class="form-group">
                            <label class="font-weight-bold">Discount (TSh)</label>
                            <input type="number" id="discount" class="form-control" value="0" min="0" step="0.01">
                        </div>
                    </div>
                    
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button type="button" id="addItemBtn" class="btn btn-primary btn-block">
                                <i class="fas fa-plus"></i> Add Item
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Items Table -->
        <div class="card mb-4">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="fas fa-shopping-cart"></i> Sale Items</h5>
                <span class="badge badge-secondary" id="itemCount">0 items</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="itemsTable">
                        <thead class="thead-dark">
                            <tr>
                                <th width="30%">Product</th>
                                <th width="15%">Batch</th>
                                <th width="10%">Qty</th>
                                <th width="15%">Price</th>
                                <th width="15%">Discount</th>
                                <th width="15%">Total</th>
                                <th width="5%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Items will be added here -->
                        </tbody>
                        <tfoot>
                            <tr class="table-info">
                                <td colspan="4" class="text-right font-weight-bold">Subtotal:</td>
                                <td id="totalDiscount" class="text-right">0.00</td>
                                <td id="subtotal" class="text-right font-weight-bold">0.00</td>
                                <td></td>
                            </tr>
                            <tr class="table-success">
                                <td colspan="5" class="text-right font-weight-bold">Grand Total:</td>
                                <td id="grandTotal" class="text-right font-weight-bold" style="font-size: 1.2em;">0.00</td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>

        <!-- Payment Section -->
        <div class="card mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-money-bill-wave"></i> Payment</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Payment Method</label>
                            <select class="form-control" name="payment_method" 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">Card</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Amount Paid (TSh)</label>
                            <input type="number" name="paid" class="form-control" value="0" min="0" step="0.01" required>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label class="font-weight-bold">Change</label>
                            <input type="text" id="changeAmount" class="form-control" readonly value="0.00">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="form-group">
            <button type="submit" class="btn btn-success btn-lg">
                <i class="fas fa-save"></i> Save Sale
            </button>
            <button type="button" class="btn btn-secondary btn-lg" onclick="clearForm()">
                <i class="fas fa-redo"></i> Clear Form
            </button>
            <a href="list_sales.php" class="btn btn-outline-secondary btn-lg">
                <i class="fas fa-times"></i> Cancel
            </a>
        </div>
    </form>
</div>

<?php require_once '../includes/footer.php'; ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
    const shop_id = <?= $shop_id ?>;
    const user_id = <?= $user_id ?>;
    let productData = {};

    function showAlert(msg, type='success', icon=''){
        const icons = {
            'success': 'fa-check-circle',
            'danger': 'fa-exclamation-circle',
            'warning': 'fa-exclamation-triangle',
            'info': 'fa-info-circle'
        };
        
        let alertId = 'alert-' + Date.now();
        let alertHTML = `
            <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show">
                <i class="fas ${icon || icons[type] || 'fa-info-circle'} mr-2"></i>
                ${msg}
                <button class="close" data-dismiss="alert">&times;</button>
            </div>
        `;
        $("#alertPlaceholder").html(alertHTML);
        setTimeout(() => $(`#${alertId}`).alert('close'), 4000);
    }

    // PRODUCT SEARCH
    $("#productSearch").on('input', function(){
        let query = $(this).val().trim();
        if(query.length < 2){ 
            $("#productResults").hide().empty(); 
            return; 
        }
        
        $.ajax({
            url: 'search_product.php',
            type: 'POST',
            data: {query: query, shop_id: shop_id},
            success: function(res){
                $("#productResults").html(res).show();
            },
            error: function(){
                showAlert('Error searching products', 'danger');
            }
        });
    });

    // Hide results when clicking outside
    $(document).on('click', function(e){
        if(!$(e.target).closest('#productSearch, #productResults').length){
            $("#productResults").hide();
        }
    });

    // SELECT PRODUCT
    $(document).on("click",".product-item",function(){
        const productId = $(this).data('id');
        const productName = $(this).data('name');
        const sku = $(this).data('sku');
        
        $("#selectedProductName").val(productName);
        $("#selectedProductId").val(productId);
        $("#productSku").text('SKU: ' + sku);
        $("#productSearch").val('');
        $("#productResults").hide().empty();
        
        // Load batches for this product
        $.ajax({
            url: 'get_product_batches.php',
            type: 'POST',
            data: {product_id: productId, shop_id: shop_id},
            dataType: 'json',
            success: function(response){
                if(response.status === 'success' && response.batches.length > 0){
                    $("#batchSelect").prop('disabled', false).empty().append('<option value="">Select Batch</option>');
                    
                    response.batches.forEach(function(batch){
                        let expiryText = batch.expiry_date ? ' (Exp: ' + batch.expiry_date + ')' : '';
                        $("#batchSelect").append(
                            `<option value="${batch.id}" 
                                     data-price="${batch.sell_price}" 
                                     data-qty="${batch.available_qty}"
                                     data-expiry="${batch.expiry_date || ''}"
                                     data-batch-no="${batch.batch_no}">
                                ${batch.batch_no} - ${batch.available_qty} pcs${expiryText}
                            </option>`
                        );
                    });
                    
                    // Select first batch by default
                    if(response.batches.length === 1){
                        $("#batchSelect").val(response.batches[0].id).trigger('change');
                    }
                } else {
                    showAlert('No available batches for this product', 'warning');
                    $("#batchSelect").prop('disabled', true).empty().append('<option value="">No batches available</option>');
                    clearProductFields();
                }
            },
            error: function(){
                showAlert('Error loading batches', 'danger');
            }
        });
    });

    // BATCH SELECTION
    $("#batchSelect").on('change', function(){
        const selectedOption = $(this).find('option:selected');
        if(selectedOption.val()){
            $("#batchId").val(selectedOption.val());
            $("#unitPrice").val(selectedOption.data('price') || '0.00');
            $("#qtyAvailable").val(selectedOption.data('qty') || '0');
            $("#expiryDate").val(selectedOption.data('expiry') || 'N/A');
            
            // Set max quantity
            $("#qty").attr('max', selectedOption.data('qty') || 0);
        } else {
            clearProductFields();
        }
    });

    function clearProductFields(){
        $("#batchId").val('');
        $("#unitPrice").val('');
        $("#qtyAvailable").val('');
        $("#expiryDate").val('');
        $("#qty").val(1).attr('max', '');
    }

    // ADD ITEM
    $("#addItemBtn").click(function(){
        const productId = $("#selectedProductId").val();
        const productName = $("#selectedProductName").val();
        const batchId = $("#batchSelect").val();
        const batchNo = $("#batchSelect option:selected").data('batch-no') || '';
        const qty = parseInt($("#qty").val()) || 0;
        const price = parseFloat($("#unitPrice").val()) || 0;
        const discount = parseFloat($("#discount").val()) || 0;
        const available = parseInt($("#qtyAvailable").val()) || 0;

        // Validation
        if(!productId){
            showAlert("Please select a product", 'warning');
            return;
        }
        if(!batchId){
            showAlert("Please select a batch", 'warning');
            return;
        }
        if(qty <= 0){
            showAlert("Please enter a valid quantity", 'warning');
            return;
        }
        if(qty > available){
            showAlert(`Only ${available} units available in this batch`, 'danger');
            return;
        }
        if(discount < 0){
            showAlert("Discount cannot be negative", 'warning');
            return;
        }
        if(discount > (qty * price)){
            showAlert("Discount cannot exceed item total", 'warning');
            return;
        }

        // Check if this batch is already in the cart
        const existingRow = $(`#itemsTable tbody tr[data-batch-id="${batchId}"]`);
        if(existingRow.length > 0){
            const existingQty = parseInt(existingRow.find('input[name*="[qty]"]').val()) || 0;
            const newQty = existingQty + qty;
            
            if(newQty > available){
                showAlert(`Cannot add ${qty} more units. Total would exceed available stock (${available})`, 'danger');
                return;
            }
            
            // Update existing row
            existingRow.find('input[name*="[qty]"]').val(newQty);
            existingRow.find('.item-qty').text(newQty);
            
            const total = (newQty * price) - discount;
            existingRow.find('input[name*="[discount]"]').val(discount);
            existingRow.find('.item-discount').text(discount.toFixed(2));
            existingRow.find('.lineTotal').text(total.toFixed(2));
        } else {
            // Add new row
            const itemCount = $("#itemsTable tbody tr").length;
            const total = (qty * price) - discount;
            
            const rowHTML = `
                <tr data-batch-id="${batchId}">
                    <td>
                        ${productName}
                        <input type="hidden" name="items[${itemCount}][product_id]" value="${productId}">
                    </td>
                    <td>
                        ${batchNo}
                        <input type="hidden" name="items[${itemCount}][batch_id]" value="${batchId}">
                    </td>
                    <td class="text-center">
                        <span class="item-qty">${qty}</span>
                        <input type="hidden" name="items[${itemCount}][qty]" value="${qty}">
                    </td>
                    <td class="text-right">
                        <span class="item-price">${price.toFixed(2)}</span>
                        <input type="hidden" name="items[${itemCount}][unit_price]" value="${price}">
                    </td>
                    <td class="text-right">
                        <span class="item-discount">${discount.toFixed(2)}</span>
                        <input type="hidden" name="items[${itemCount}][discount]" value="${discount}">
                    </td>
                    <td class="text-right font-weight-bold lineTotal">${total.toFixed(2)}</td>
                    <td class="text-center">
                        <button type="button" class="btn btn-danger btn-sm remove-item" title="Remove item">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
            
            $("#itemsTable tbody").append(rowHTML);
        }

        // Clear form and recalculate
        clearProductSelection();
        calculateTotals();
    });

    function clearProductSelection(){
        $("#selectedProductName").val('');
        $("#selectedProductId").val('');
        $("#productSku").text('');
        $("#batchSelect").prop('disabled', true).val('');
        $("#batchId").val('');
        $("#unitPrice").val('');
        $("#qtyAvailable").val('');
        $("#expiryDate").val('');
        $("#qty").val(1).attr('max', '');
        $("#discount").val(0);
        $("#productSearch").val('');
    }

    // REMOVE ITEM
    $(document).on("click", ".remove-item", function(){
        $(this).closest('tr').remove();
        calculateTotals();
    });

    // CALCULATE TOTALS
    function calculateTotals(){
        let subtotal = 0;
        let totalDiscount = 0;
        
        $("#itemsTable tbody tr").each(function(){
            const qty = parseInt($(this).find('input[name*="[qty]"]').val()) || 0;
            const price = parseFloat($(this).find('input[name*="[unit_price]"]').val()) || 0;
            const discount = parseFloat($(this).find('input[name*="[discount]"]').val()) || 0;
            
            subtotal += qty * price;
            totalDiscount += discount;
            
            const lineTotal = (qty * price) - discount;
            $(this).find('.lineTotal').text(lineTotal.toFixed(2));
        });
        
        const grandTotal = subtotal - totalDiscount;
        
        $("#subtotal").text(subtotal.toFixed(2));
        $("#totalDiscount").text(totalDiscount.toFixed(2));
        $("#grandTotal").text(grandTotal.toFixed(2));
        $("#itemCount").text($("#itemsTable tbody tr").length + ' items');
        
        // Calculate change
        const paid = parseFloat($("input[name='paid']").val()) || 0;
        const change = paid - grandTotal;
        $("#changeAmount").val(change >= 0 ? change.toFixed(2) : '0.00');
    }

    // Update change when paid amount changes
    $("input[name='paid']").on('input', calculateTotals);

    // CLEAR FORM
    function clearForm(){
        if(confirm('Are you sure you want to clear the entire form? This cannot be undone.')){
            $("#saleForm")[0].reset();
            $("#itemsTable tbody").empty();
            clearProductSelection();
            calculateTotals();
            showAlert('Form cleared', 'info');
        }
    }

    // FORM SUBMISSION
    $("#saleForm").submit(function(e){
        e.preventDefault();
        
        // Validate
        if($("#itemsTable tbody tr").length === 0){
            showAlert("Please add at least one item to the sale", 'warning');
            return;
        }
        
        const paid = parseFloat($("input[name='paid']").val()) || 0;
        const grandTotal = parseFloat($("#grandTotal").text()) || 0;
        
        if(paid < grandTotal){
            if(!confirm(`Amount paid (${paid}) is less than total (${grandTotal}). Do you want to continue with partial payment?`)){
                return;
            }
        }
        
        // Show loading
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
        
        // Prepare form data
        const formData = $(this).serialize();
        
        $.ajax({
            url: 'save_sale.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response){
                if(response.status === 'success'){
                    showAlert(response.message, 'success', 'fa-check-circle');
                    
                    // Store success message
                    sessionStorage.setItem('sale_success', response.message);
                    
                    // Open print window
                    setTimeout(() => {
                        window.open("print_invoice.php?id=" + response.sale_id, "_blank");
                        window.location.href = "list_sales.php?added=1&id=" + response.sale_id;
                    }, 1500);
                } else {
                    showAlert(response.message, 'danger');
                    submitBtn.prop('disabled', false).html(originalText);
                }
            },
            error: function(xhr, status, error){
                console.error('Sale save error:', error);
                showAlert('An error occurred while saving the sale. Please try again.', 'danger');
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Initialize
    calculateTotals();
});
</script>