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

// Ensure session has shop assigned
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-ban'></i> Shop or user session not assigned. Please contact admin.
            </div>
          </div>";
    require_once '../includes/footer.php';
    exit();
}

$shop_id    = $_SESSION['user']['shop_id'];
$created_by = $_SESSION['user']['id'];
$shop_name = $_SESSION['user']['shop_name'] ?? 'Your Shop';

// Check if product_id is passed in URL
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;

// Fetch suppliers
$supplierStmt = $pdo->query("SELECT id, name FROM suppliers ORDER BY name");
$suppliers = $supplierStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch active products for this shop
$productStmt = $pdo->prepare("SELECT id, name, unit, buying_price, selling_price FROM products WHERE shop_id=? AND is_active=1 ORDER BY name");
$productStmt->execute([$shop_id]);
$products = $productStmt->fetchAll(PDO::FETCH_ASSOC);

// If specific product is requested, get its details
$selected_product = null;
if ($product_id > 0) {
    foreach ($products as $product) {
        if ($product['id'] == $product_id) {
            $selected_product = $product;
            break;
        }
    }
}
?>

<style>
/* SweetAlert Custom Styles */
.swal2-popup {
    border-radius: 12px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.swal2-title {
    font-size: 1.5rem;
    font-weight: 600;
}

.swal2-confirm {
    border-radius: 8px;
    padding: 10px 24px;
    font-weight: 500;
}

.swal2-cancel {
    border-radius: 8px;
    padding: 10px 24px;
    font-weight: 500;
}

/* Custom Styles */
.table-warning {
    background-color: #fff3cd !important;
    border-color: #ffeaa7 !important;
}

.table-success {
    background-color: #d4edda !important;
    border-color: #c3e6cb !important;
}

.price-input-group .input-group-text {
    background-color: #f8f9fa;
    border-color: #ced4da;
    font-weight: 500;
}

.batch-input {
    font-family: 'Courier New', monospace;
    font-weight: 500;
}

.btn-action {
    padding: 5px 10px;
    border-radius: 6px;
    transition: all 0.2s ease;
}

.btn-action:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.card {
    border: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
    border-radius: 12px;
    margin-bottom: 20px;
}

.card-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0 !important;
    padding: 15px 20px;
}

.card-header h5 {
    margin-bottom: 0;
    font-weight: 600;
}

.required-asterisk {
    color: #dc3545;
    font-weight: bold;
}

/* Summary Card */
.summary-value {
    font-size: 1.5rem;
    font-weight: 700;
    color: #2c3e50;
}

.summary-label {
    color: #7f8c8d;
    font-size: 0.9rem;
    text-transform: uppercase;
    letter-spacing: 1px;
}

/* Animation for new rows */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

.new-row {
    animation: fadeIn 0.3s ease;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .table-responsive {
        font-size: 14px;
    }
    
    .btn-lg {
        padding: 8px 16px;
        font-size: 14px;
    }
}
</style>

<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

<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-cart-plus"></i> New Purchase
        </h3>
        <div>
            <span class="badge badge-info p-2">
                <i class="fas fa-store"></i> Shop: <?= htmlspecialchars($shop_name) ?>
            </span>
            <?php if ($selected_product): ?>
            <span class="badge badge-success p-2 ml-2">
                <i class="fas fa-box"></i> Product: <?= htmlspecialchars($selected_product['name']) ?>
            </span>
            <?php endif; ?>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-info-circle"></i> Purchase Information</h5>
        </div>
        <div class="card-body">
            <form id="purchaseForm">
                <input type="hidden" name="shop_id" value="<?= $shop_id ?>">
                <input type="hidden" name="created_by" value="<?= $created_by ?>">

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Supplier <span class="required-asterisk">*</span></label>
                        <select name="supplier_id" class="form-control" id="supplierSelect" required>
                            <option value="">-- Select Supplier --</option>
                            <?php foreach ($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <small class="form-text text-muted">Choose a supplier from the list</small>
                    </div>
                    
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Invoice Number <span class="required-asterisk">*</span></label>
                        <input type="text" name="invoice_no" class="form-control" id="invoiceNo" required 
                               placeholder="e.g., INV-20250101-001">
                        <small class="form-text text-muted">Enter the supplier's invoice number</small>
                    </div>
                    
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold">Purchase Date <span class="required-asterisk">*</span></label>
                        <input type="date" name="purchase_date" class="form-control" id="purchaseDate" required 
                               value="<?= date('Y-m-d') ?>">
                        <small class="form-text text-muted">Date of purchase</small>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-boxes"></i> Purchase Items</h5>
            <div>
                <button type="button" class="btn btn-primary btn-sm" onclick="addRow()" id="addItemBtn">
                    <i class="fas fa-plus"></i> Add Item
                </button>
                <button type="button" class="btn btn-outline-info btn-sm ml-2" onclick="addMultipleRows(3)">
                    <i class="fas fa-layer-group"></i> Add 3 Items
                </button>
            </div>
        </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="25%">Product <span class="required-asterisk">*</span></th>
                            <th width="15%">Batch No <span class="required-asterisk">*</span></th>
                            <th width="10%">Quantity <span class="required-asterisk">*</span></th>
                            <th width="15%">Cost Price <span class="required-asterisk">*</span></th>
                            <th width="15%">Selling Price <span class="required-asterisk">*</span></th>
                            <th width="15%">Expiry Date</th>
                            <th width="5%" class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Items will be added here dynamically -->
                    </tbody>
                    <tfoot id="summaryFooter" style="display: none;">
                        <tr class="table-secondary">
                            <td colspan="2" class="text-right"><strong>Summary:</strong></td>
                            <td class="text-center"><strong id="totalItems">0</strong></td>
                            <td class="text-right"><strong id="totalCost">0.00</strong></td>
                            <td class="text-right"><strong id="totalSell">0.00</strong></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            
            <!-- No items message -->
            <div id="noItemsMessage" class="text-center py-5">
                <i class="fas fa-box-open fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">No Items Added Yet</h5>
                <p class="text-muted mb-3">Click "Add Item" button above to start adding products to your purchase.</p>
                <button type="button" class="btn btn-primary" onclick="addRow()">
                    <i class="fas fa-plus"></i> Add Your First Item
                </button>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-calculator"></i> Purchase Summary</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <div class="text-center p-3 bg-light rounded">
                        <div class="summary-label">Total Items</div>
                        <div class="summary-value" id="itemCountDisplay">0</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center p-3 bg-light rounded">
                        <div class="summary-label">Total Quantity</div>
                        <div class="summary-value" id="totalQtyDisplay">0</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center p-3 bg-light rounded">
                        <div class="summary-label">Total Cost</div>
                        <div class="summary-value" id="totalCostDisplay">0.00</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="text-center p-3 bg-light rounded">
                        <div class="summary-label">Total Value</div>
                        <div class="summary-value" id="totalSellDisplay">0.00</div>
                    </div>
                </div>
            </div>
            
            <div class="form-group mt-4">
                <label class="font-weight-bold">Notes (Optional)</label>
                <textarea name="notes" id="purchaseNotes" class="form-control" rows="3" 
                          placeholder="Any additional notes about this purchase..."></textarea>
                <small class="form-text text-muted">You can add special instructions, payment terms, or other relevant information here.</small>
            </div>
            
            <hr class="my-4">
            
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <button type="button" class="btn btn-outline-secondary" onclick="clearForm()">
                        <i class="fas fa-redo"></i> Clear Form
                    </button>
                    <a href="list_purchases.php" class="btn btn-outline-danger ml-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
                <div>
                    <button type="button" id="savePurchaseBtn" class="btn btn-success btn-lg px-5">
                        <i class="fas fa-save"></i> Save Purchase
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const products = <?= json_encode($products) ?>;
let rowCounter = 0;
let selectedProductId = <?= $product_id ?>;
let isInitialLoad = true; // Flag to track initial page load

function showSuccessAlert(message, title = 'Success!') {
    Swal.fire({
        title: title,
        text: message,
        icon: 'success',
        timer: 3000,
        timerProgressBar: true,
        showConfirmButton: false,
        toast: true,
        position: 'top-end',
        background: '#d4edda',
        iconColor: '#155724'
    });
}

function showErrorAlert(message, title = 'Error!') {
    Swal.fire({
        title: title,
        text: message,
        icon: 'error',
        timer: 4000,
        timerProgressBar: true,
        showConfirmButton: true,
        confirmButtonText: 'OK',
        confirmButtonColor: '#dc3545'
    });
}

function showWarningAlert(message, title = 'Warning!') {
    Swal.fire({
        title: title,
        text: message,
        icon: 'warning',
        timer: 3000,
        timerProgressBar: true,
        showConfirmButton: false,
        toast: true,
        position: 'top-end'
    });
}

function showInfoAlert(message, title = 'Info') {
    Swal.fire({
        title: title,
        text: message,
        icon: 'info',
        timer: 3000,
        timerProgressBar: true,
        showConfirmButton: false,
        toast: true,
        position: 'top-end'
    });
}

function showLoadingAlert(title = 'Processing...') {
    Swal.fire({
        title: title,
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => {
            Swal.showLoading();
        }
    });
}

function addRow(productId = null, prefillData = null, suppressAlert = false) {
    rowCounter++;
    
    // Get product options
    let productOptions = '<option value="">-- Select Product --</option>';
    products.forEach(product => {
        let selected = '';
        if (productId && product.id == productId) {
            selected = 'selected';
        }
        productOptions += `<option value="${product.id}" data-unit="${product.unit || 'unit'}" ${selected}>${product.name} (${product.unit || 'unit'})</option>`;
    });
    
    let row = `
    <tr id="row-${rowCounter}" data-row-id="${rowCounter}" class="new-row">
        <td>
            <select name="product_id[]" class="form-control product-select" required onchange="onProductChange(${rowCounter})">
                ${productOptions}
            </select>
        </td>
        <td>
            <input type="text" name="batch_no[]" class="form-control batch-no batch-input" required 
                   placeholder="e.g., BATCH-001" value="${prefillData?.batch || ''}">
        </td>
        <td>
            <input type="number" name="qty[]" class="form-control qty" min="1" required 
                   onchange="calculateTotals()" onkeyup="calculateTotals()" value="${prefillData?.qty || '1'}">
        </td>
        <td>
            <div class="input-group price-input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">TSh</span>
                </div>
                <input type="number" name="cost_price[]" class="form-control cost" step="0.01" min="0.01" required 
                       onchange="calculateTotals()" onkeyup="calculateTotals()" value="${prefillData?.cost || ''}">
            </div>
        </td>
        <td>
            <div class="input-group price-input-group">
                <div class="input-group-prepend">
                    <span class="input-group-text">TSh</span>
                </div>
                <input type="number" name="sell_price[]" class="form-control sell" step="0.01" min="0.01" required 
                       value="${prefillData?.sell || ''}">
            </div>
        </td>
        <td>
            <input type="date" name="expiry_date[]" class="form-control expiry" 
                   value="${prefillData?.expiry || ''}">
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm btn-action" onclick="removeRow(${rowCounter})" 
                    title="Remove item">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>`;
    
    $('#itemsTable tbody').append(row);
    $('#noItemsMessage').hide();
    $('#summaryFooter').show();
    
    // Add fade-in animation class, then remove it
    setTimeout(() => {
        $(`#row-${rowCounter}`).removeClass('new-row');
    }, 300);
    
    updateItemCount();
    calculateTotals();
    
    // If this is a new row with product selected, auto-fill prices
    if (productId || prefillData) {
        onProductChange(rowCounter);
    }
    
    // Only show success alert if not suppressing (like on initial load)
    if (!suppressAlert && !isInitialLoad) {
        showSuccessAlert('Item added successfully!');
    }
}

function addMultipleRows(count) {
    Swal.fire({
        title: `Add ${count} Items`,
        text: `Are you sure you want to add ${count} empty items to the table?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, add them',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#28a745'
    }).then((result) => {
        if (result.isConfirmed) {
            for (let i = 0; i < count; i++) {
                addRow();
            }
            showSuccessAlert(`${count} items added successfully!`);
        }
    });
}

function removeRow(rowId) {
    Swal.fire({
        title: 'Remove Item',
        text: 'Are you sure you want to remove this item?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, remove it',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#dc3545'
    }).then((result) => {
        if (result.isConfirmed) {
            $(`#row-${rowId}`).fadeOut(300, function() {
                $(this).remove();
                calculateTotals();
                updateItemCount();
                
                // Show no items message if table is empty
                if ($('#itemsTable tbody tr').length === 0) {
                    $('#noItemsMessage').show();
                    $('#summaryFooter').hide();
                }
                
                showSuccessAlert('Item removed successfully!');
            });
        }
    });
}

function onProductChange(rowId) {
    const row = $(`#row-${rowId}`);
    const productId = row.find('.product-select').val();
    const costInput = row.find('.cost');
    const sellInput = row.find('.sell');
    
    if (productId) {
        // Find the selected product
        const product = products.find(p => p.id == productId);
        if (product) {
            // Auto-fill prices if empty
            if (!costInput.val() && product.buying_price > 0) {
                costInput.val(product.buying_price);
                calculateTotals();
            }
            
            if (!sellInput.val() && product.selling_price > 0) {
                sellInput.val(product.selling_price);
            }
            
            // Auto-generate batch number if empty
            const batchInput = row.find('.batch-no');
            if (!batchInput.val()) {
                const date = new Date();
                const batchNo = `BATCH-${date.getFullYear()}${('0' + (date.getMonth() + 1)).slice(-2)}${('0' + date.getDate()).slice(-2)}-${Math.floor(Math.random() * 1000)}`;
                batchInput.val(batchNo);
            }
        }
    }
}

function calculateTotals() {
    let totalItems = 0;
    let totalQty = 0;
    let totalCost = 0;
    let totalSell = 0;
    
    $('#itemsTable tbody tr').each(function() {
        let qty = parseFloat($(this).find('.qty').val()) || 0;
        let cost = parseFloat($(this).find('.cost').val()) || 0;
        let sell = parseFloat($(this).find('.sell').val()) || 0;
        
        if (qty > 0) {
            totalItems++;
            totalQty += qty;
            totalCost += qty * cost;
            totalSell += qty * sell;
        }
    });
    
    // Update summary displays
    $('#itemCountDisplay').text(totalItems);
    $('#totalQtyDisplay').text(totalQty);
    $('#totalCostDisplay').text(totalCost.toFixed(2));
    $('#totalSellDisplay').text(totalSell.toFixed(2));
    
    // Update footer summary
    $('#totalItems').text(totalQty);
    $('#totalCost').text(totalCost.toFixed(2));
    $('#totalSell').text(totalSell.toFixed(2));
}

function updateItemCount() {
    let count = $('#itemsTable tbody tr').length;
    $('#itemCountDisplay').text(count);
}

function clearForm() {
    Swal.fire({
        title: 'Clear Form',
        text: 'Are you sure you want to clear all fields? This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, clear all',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#dc3545',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            $('#supplierSelect').val('');
            $('#invoiceNo').val('');
            $('#purchaseDate').val('<?= date('Y-m-d') ?>');
            $('#purchaseNotes').val('');
            $('#itemsTable tbody').empty();
            $('#noItemsMessage').show();
            $('#summaryFooter').hide();
            rowCounter = 0;
            
            // Reset summary displays
            $('#itemCountDisplay').text('0');
            $('#totalQtyDisplay').text('0');
            $('#totalCostDisplay').text('0.00');
            $('#totalSellDisplay').text('0.00');
            
            showSuccessAlert('Form cleared successfully!');
        }
    });
}

function validateForm() {
    // Validate supplier
    let supplier = $('#supplierSelect').val();
    if (!supplier) {
        showErrorAlert('Please select a supplier.', 'Missing Supplier');
        $('#supplierSelect').focus();
        return false;
    }
    
    // Validate invoice number
    let invoiceNo = $('#invoiceNo').val().trim();
    if (!invoiceNo) {
        showErrorAlert('Please enter an invoice number.', 'Missing Invoice Number');
        $('#invoiceNo').focus();
        return false;
    }
    
    // Validate at least one item
    if ($('#itemsTable tbody tr').length === 0) {
        showErrorAlert('Please add at least one item to the purchase.', 'No Items');
        return false;
    }
    
    // Validate all items have required fields
    let isValid = true;
    let invalidRows = [];
    
    $('#itemsTable tbody tr').each(function(index) {
        let product = $(this).find('.product-select').val();
        let batch = $(this).find('.batch-no').val().trim();
        let qty = $(this).find('.qty').val();
        let cost = $(this).find('.cost').val();
        let sell = $(this).find('.sell').val();
        
        if (!product || !batch || !qty || !cost || !sell) {
            isValid = false;
            invalidRows.push(index + 1);
            $(this).addClass('table-warning');
        } else {
            $(this).removeClass('table-warning');
        }
    });
    
    if (!isValid) {
        showErrorAlert(`Please fill all required fields for items: ${invalidRows.join(', ')}`, 'Incomplete Items');
        return false;
    }
    
    return true;
}

function collectFormData() {
    let formData = new FormData();
    
    // Add basic form data
    formData.append('shop_id', <?= $shop_id ?>);
    formData.append('created_by', <?= $created_by ?>);
    formData.append('supplier_id', $('#supplierSelect').val());
    formData.append('invoice_no', $('#invoiceNo').val().trim());
    formData.append('purchase_date', $('#purchaseDate').val());
    
    // Add notes if any
    let notes = $('#purchaseNotes').val().trim();
    if (notes) {
        formData.append('notes', notes);
    }
    
    // Collect all items
    let productIds = [];
    let batchNos = [];
    let qtys = [];
    let costPrices = [];
    let sellPrices = [];
    let expiryDates = [];
    
    $('#itemsTable tbody tr').each(function() {
        productIds.push($(this).find('.product-select').val());
        batchNos.push($(this).find('.batch-no').val());
        qtys.push($(this).find('.qty').val());
        costPrices.push($(this).find('.cost').val());
        sellPrices.push($(this).find('.sell').val());
        
        let expiry = $(this).find('.expiry').val();
        expiryDates.push(expiry ? expiry : '');
    });
    
    // Add arrays to formData
    productIds.forEach((value, index) => {
        formData.append('product_id[]', value);
        formData.append('batch_no[]', batchNos[index]);
        formData.append('qty[]', qtys[index]);
        formData.append('cost_price[]', costPrices[index]);
        formData.append('sell_price[]', sellPrices[index]);
        formData.append('expiry_date[]', expiryDates[index]);
    });
    
    return formData;
}

// Initialize page
$(document).ready(function() {
    console.log('Page loaded. Products available:', products.length);
    
    // Auto-generate invoice number if empty
    $('#invoiceNo').on('blur', function() {
        if (!$(this).val().trim()) {
            let date = new Date();
            let invoiceNo = 'INV-' + date.getFullYear() + 
                           ('0' + (date.getMonth() + 1)).slice(-2) + 
                           ('0' + date.getDate()).slice(-2) + 
                           '-' + Math.floor(Math.random() * 1000);
            $(this).val(invoiceNo);
            if (!isInitialLoad) {
                showInfoAlert('Invoice number auto-generated');
            }
        }
    });
    
    // Auto-calculate selling price based on cost price
    $(document).on('change', '.cost', function() {
        let cost = parseFloat($(this).val()) || 0;
        let sellPriceField = $(this).closest('tr').find('.sell');
        
        // Only auto-calculate if sell price is empty or zero
        if (!sellPriceField.val() || parseFloat(sellPriceField.val()) === 0) {
            // Add 30% markup by default
            let sellPrice = cost * 1.3;
            sellPriceField.val(sellPrice.toFixed(2));
            if (!isInitialLoad) {
                showInfoAlert('Selling price auto-calculated with 30% markup');
            }
        }
    });
    
    // Auto-generate expiry date if empty (set to 1 year from today)
    $(document).on('focus', '.expiry', function() {
        if (!$(this).val()) {
            let today = new Date();
            let oneYearLater = new Date(today.setFullYear(today.getFullYear() + 1));
            let formattedDate = oneYearLater.toISOString().split('T')[0];
            $(this).val(formattedDate);
            if (!isInitialLoad) {
                showInfoAlert('Expiry date set to 1 year from today');
            }
        }
    });
    
    // Save purchase button click handler
    $('#savePurchaseBtn').on('click', function(e) {
        e.preventDefault();
        
        console.log('Save button clicked');
        
        // Validate form
        if (!validateForm()) {
            return;
        }
        
        Swal.fire({
            title: 'Save Purchase',
            text: 'Are you sure you want to save this purchase?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, save it',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#28a745',
            reverseButtons: true,
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return new Promise((resolve, reject) => {
                    // Show loading
                    let submitBtn = $(this);
                    let originalText = submitBtn.html();
                    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                    
                    // Collect form data
                    let formData = collectFormData();
                    
                    // Send AJAX request
                    $.ajax({
                        url: 'save_purchase.php',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        dataType: 'json',
                        success: function(response) {
                            console.log('AJAX Success Response:', response);
                            
                            if (response.status === 'success') {
                                resolve(response);
                            } else {
                                reject(new Error(response.message || 'Unknown error'));
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error Details:', {xhr, status, error});
                            
                            let errorMsg = 'An error occurred while saving the purchase.';
                            if (xhr.responseText) {
                                try {
                                    let errorResponse = JSON.parse(xhr.responseText);
                                    errorMsg = errorResponse.message || errorMsg;
                                } catch (e) {
                                    errorMsg = xhr.responseText.substring(0, 100) + '...';
                                }
                            }
                            
                            reject(new Error(errorMsg));
                        },
                        complete: function() {
                            submitBtn.prop('disabled', false).html('<i class="fas fa-save"></i> Save Purchase');
                        }
                    });
                });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                const response = result.value;
                
                Swal.fire({
                    title: 'Success!',
                    text: response.message,
                    icon: 'success',
                    showCancelButton: true,
                    confirmButtonText: 'View Purchase',
                    cancelButtonText: 'Add Another',
                    confirmButtonColor: '#28a745',
                    showDenyButton: true,
                    denyButtonText: 'Print Receipt'
                }).then((result2) => {
                    if (result2.isConfirmed) {
                        // Redirect to view purchase
                        window.location.href = 'list_purchases.php?added=1&id=' + response.purchase_id;
                    } else if (result2.isDenied) {
                        // Print receipt (you can implement this)
                        window.open('print_purchase.php?id=' + response.purchase_id, '_blank');
                        // Stay on page for another entry
                        clearForm();
                    } else {
                        // Stay on page for another entry
                        clearForm();
                    }
                });
            }
        }).catch((error) => {
            Swal.fire({
                title: 'Error!',
                text: error.message,
                icon: 'error',
                confirmButtonText: 'OK',
                confirmButtonColor: '#dc3545'
            });
        });
    });
    
    // Initialize with one row, pre-select product if provided
    setTimeout(() => {
        if (selectedProductId > 0 && products.find(p => p.id == selectedProductId)) {
            // Pre-fill with the selected product (suppress alert on initial load)
            addRow(selectedProductId, {
                qty: 1,
                batch: 'BATCH-001'
            }, true); // true = suppress alert
        } else {
            // Add empty row (suppress alert on initial load)
            addRow(null, null, true); // true = suppress alert
        }
        
        // After initial load, set flag to false so future actions show alerts
        setTimeout(() => {
            isInitialLoad = false;
        }, 100);
    }, 500);
    
    // Set today's date as default
    $('#purchaseDate').val('<?= date('Y-m-d') ?>');
    
    // Auto-generate a default invoice number
    setTimeout(() => {
        if (!$('#invoiceNo').val().trim()) {
            let date = new Date();
            let invoiceNo = 'INV-' + date.getFullYear() + 
                           ('0' + (date.getMonth() + 1)).slice(-2) + 
                           ('0' + date.getDate()).slice(-2) + 
                           '-001';
            $('#invoiceNo').val(invoiceNo);
        }
    }, 1000);
});

// REMOVED: The annoying "Changes you made may not be saved" warning
// Users can now navigate away without being bothered by the browser warning
</script>

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