<?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 alert-dismissible fade show shadow' role='alert'>
                <div class='d-flex align-items-center'>
                    <i class='fas fa-ban fa-lg mr-3'></i>
                    <div>
                        <h5 class='alert-heading mb-1'>Session Error</h5>
                        <p class='mb-0'>Shop or user session not assigned. Please contact administrator.</p>
                    </div>
                </div>
                <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                    <span aria-hidden='true'>&times;</span>
                </button>
            </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';

// 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 FROM products WHERE shop_id=? AND is_active=1 ORDER BY name");
$productStmt->execute([$shop_id]);
$products = $productStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- Add SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<!-- Add Animate.css for animations -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <!-- Page Header with Animation -->
    <div class="d-flex justify-content-between align-items-center mb-4 animate__animated animate__fadeInDown">
        <div>
            <h3 class="text-primary mb-1">
                <i class="fas fa-cart-plus mr-2"></i> New Purchase Order
            </h3>
            <p class="text-muted mb-0">Create a new purchase from your suppliers</p>
        </div>
        <div>
            <span class="badge badge-pill badge-info p-3 shadow-sm">
                <i class="fas fa-store mr-2"></i> <?= htmlspecialchars($shop_name) ?>
            </span>
        </div>
    </div>

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

    <!-- Purchase Information Card -->
    <div class="card shadow-lg border-0 mb-4 animate__animated animate__fadeInUp">
        <div class="card-header bg-gradient-primary text-white">
            <h5 class="mb-0">
                <i class="fas fa-info-circle mr-2"></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 text-primary">
                            <i class="fas fa-truck mr-1"></i> Supplier <span class="text-danger">*</span>
                        </label>
                        <select name="supplier_id" class="form-control shadow-sm" 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">
                            <i class="fas fa-info-circle mr-1"></i> Choose a supplier from the list
                        </small>
                    </div>
                    
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold text-primary">
                            <i class="fas fa-file-invoice mr-1"></i> Invoice Number <span class="text-danger">*</span>
                        </label>
                        <div class="input-group shadow-sm">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-hashtag"></i>
                                </span>
                            </div>
                            <input type="text" name="invoice_no" class="form-control" id="invoiceNo" required 
                                   placeholder="e.g., INV-20250101-001">
                        </div>
                        <small class="form-text text-muted">
                            <i class="fas fa-info-circle mr-1"></i> Enter the supplier's invoice number
                        </small>
                    </div>
                    
                    <div class="col-md-4 mb-3">
                        <label class="font-weight-bold text-primary">
                            <i class="fas fa-calendar-alt mr-1"></i> Purchase Date <span class="text-danger">*</span>
                        </label>
                        <div class="input-group shadow-sm">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-calendar"></i>
                                </span>
                            </div>
                            <input type="date" name="purchase_date" class="form-control" id="purchaseDate" required 
                                   value="<?= date('Y-m-d') ?>">
                        </div>
                        <small class="form-text text-muted">
                            <i class="fas fa-info-circle mr-1"></i> Date of purchase
                        </small>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Purchase Items Card -->
    <div class="card shadow-lg border-0 mb-4 animate__animated animate__fadeInUp">
        <div class="card-header bg-gradient-info text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="fas fa-boxes mr-2"></i> Purchase Items
                <span class="badge badge-light ml-2" id="itemCountBadge">0 items</span>
            </h5>
            <button type="button" class="btn btn-light btn-sm shadow-sm" onclick="addRow()">
                <i class="fas fa-plus-circle mr-1"></i> Add New Item
            </button>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="itemsTable">
                    <thead class="thead-light">
                        <tr>
                            <th width="25%" class="border-top-0">
                                <i class="fas fa-pills mr-1"></i> Product
                            </th>
                            <th width="15%" class="border-top-0">
                                <i class="fas fa-barcode mr-1"></i> Batch No
                            </th>
                            <th width="10%" class="border-top-0">
                                <i class="fas fa-cubes mr-1"></i> Quantity
                            </th>
                            <th width="15%" class="border-top-0">
                                <i class="fas fa-money-bill-wave mr-1"></i> Cost Price
                            </th>
                            <th width="15%" class="border-top-0">
                                <i class="fas fa-tag mr-1"></i> Selling Price
                            </th>
                            <th width="15%" class="border-top-0">
                                <i class="fas fa-calendar-times mr-1"></i> Expiry Date
                            </th>
                            <th width="5%" class="border-top-0 text-center">
                                <i class="fas fa-cog"></i>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Items will be added here dynamically -->
                    </tbody>
                </table>
            </div>
            
            <!-- No items message -->
            <div id="noItemsMessage" class="text-center py-5">
                <div class="animate__animated animate__pulse">
                    <i class="fas fa-box-open fa-4x text-muted mb-4 opacity-50"></i>
                    <h4 class="text-muted font-weight-light">No items added yet</h4>
                    <p class="text-muted">Click the "Add New Item" button to start adding products</p>
                    <button type="button" class="btn btn-outline-primary mt-2" onclick="addRow()">
                        <i class="fas fa-plus mr-1"></i> Add First Item
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Purchase Summary Card -->
    <div class="card shadow-lg border-0 animate__animated animate__fadeInUp">
        <div class="card-header bg-gradient-success text-white">
            <h5 class="mb-0">
                <i class="fas fa-calculator mr-2"></i> Purchase Summary
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="font-weight-bold text-success">
                            <i class="fas fa-list-ol mr-1"></i> Total Items
                        </label>
                        <div class="input-group shadow-sm">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-box"></i>
                                </span>
                            </div>
                            <input type="text" id="itemCount" class="form-control" readonly value="0">
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="font-weight-bold text-success">
                            <i class="fas fa-money-check-alt mr-1"></i> Total Amount
                        </label>
                        <div class="input-group shadow-sm">
                            <div class="input-group-prepend">
                                <span class="input-group-text bg-light">
                                    <i class="fas fa-dollar-sign"></i>
                                </span>
                            </div>
                            <input type="text" id="total" name="total" class="form-control font-weight-bold text-success" readonly value="0.00">
                            <div class="input-group-append">
                                <span class="input-group-text bg-light">TSh</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group mt-3">
                <label class="font-weight-bold">
                    <i class="fas fa-sticky-note mr-1"></i> Notes (Optional)
                </label>
                <div class="input-group shadow-sm">
                    <div class="input-group-prepend">
                        <span class="input-group-text bg-light">
                            <i class="fas fa-edit"></i>
                        </span>
                    </div>
                    <textarea name="notes" id="purchaseNotes" class="form-control" rows="2" 
                              placeholder="Any additional notes about this purchase..."></textarea>
                </div>
            </div>
            
            <div class="form-group mt-4 d-flex justify-content-between">
                <div>
                    <button type="button" id="savePurchaseBtn" class="btn btn-success btn-lg shadow-sm">
                        <i class="fas fa-save mr-2"></i> Save Purchase
                    </button>
                    <button type="button" class="btn btn-outline-info btn-lg shadow-sm ml-2" onclick="showPreviewModal()">
                        <i class="fas fa-eye mr-2"></i> Preview
                    </button>
                </div>
                <div>
                    <a href="list_purchases.php" class="btn btn-outline-secondary btn-lg shadow-sm">
                        <i class="fas fa-times mr-2"></i> Cancel
                    </a>
                    <button type="button" class="btn btn-outline-warning btn-lg shadow-sm ml-2" onclick="showClearFormConfirmation()">
                        <i class="fas fa-redo mr-2"></i> Clear Form
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast Container -->
<div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-gradient-primary text-white">
                <h5 class="modal-title" id="previewModalLabel">
                    <i class="fas fa-eye mr-2"></i> Purchase Preview
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="previewContent">
                    <!-- Preview content will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    <i class="fas fa-times mr-2"></i> Close
                </button>
                <button type="button" class="btn btn-primary" onclick="savePurchase()">
                    <i class="fas fa-check mr-2"></i> Confirm & Save
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Loading Overlay -->
<div id="loadingOverlay" class="d-none" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.8); z-index: 9999; display: flex; justify-content: center; align-items: center;">
    <div class="text-center">
        <div class="spinner-border text-primary" style="width: 4rem; height: 4rem;" role="status">
            <span class="sr-only">Loading...</span>
        </div>
        <h4 class="mt-3 text-primary">Saving Purchase...</h4>
        <p class="text-muted">Please wait while we process your request</p>
    </div>
</div>

<!-- Add 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 src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const products = <?= json_encode($products) ?>;
let rowCounter = 0;

// Beautiful Toast Notification System
function showToast(message, type = 'success', icon = '', duration = 4000) {
    const icons = {
        'success': 'fa-check-circle',
        'danger': 'fa-exclamation-circle',
        'warning': 'fa-exclamation-triangle',
        'info': 'fa-info-circle',
        'primary': 'fa-bell'
    };
    
    const colors = {
        'success': '#28a745',
        'danger': '#dc3545',
        'warning': '#ffc107',
        'info': '#17a2b8',
        'primary': '#007bff'
    };
    
    let toastId = 'toast-' + Date.now();
    let toastHTML = `
        <div id="${toastId}" class="toast-alert animate__animated animate__slideInRight animate__faster" 
             style="min-width: 350px; margin-bottom: 10px; background: white; border-left: 5px solid ${colors[type] || colors.info}; 
                    border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); overflow: hidden;">
            <div class="d-flex align-items-center p-3">
                <div class="toast-icon mr-3" style="color: ${colors[type] || colors.info}; font-size: 1.5rem;">
                    <i class="fas ${icon || icons[type] || 'fa-info-circle'}"></i>
                </div>
                <div class="flex-grow-1">
                    <div class="toast-title mb-1" style="font-weight: 600; color: #333;">
                        ${type.charAt(0).toUpperCase() + type.slice(1)}
                    </div>
                    <div class="toast-message" style="color: #666; font-size: 0.9rem;">
                        ${message}
                    </div>
                </div>
                <button type="button" class="close ml-3" onclick="$('#${toastId}').remove()" 
                        style="color: #999; font-size: 1.2rem; background: none; border: none; cursor: pointer;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="toast-progress" style="height: 3px; background: ${colors[type] || colors.info}; width: 100%;"></div>
        </div>`;
    
    $('#toastContainer').append(toastHTML);
    
    // Progress bar animation
    $(`#${toastId} .toast-progress`).animate({ width: '0%' }, duration, 'linear', function() {
        $(`#${toastId}`).animate({ opacity: 0, marginRight: '-100%' }, 300, function() {
            $(this).remove();
        });
    });
    
    // Auto remove after duration
    setTimeout(() => {
        $(`#${toastId}`).animate({ opacity: 0, marginRight: '-100%' }, 300, function() {
            $(this).remove();
        });
    }, duration);
}

// Show loading overlay
function showLoading(message = 'Processing...') {
    $('#loadingOverlay').removeClass('d-none').addClass('d-flex');
    $('#loadingOverlay h4').text(message);
}

// Hide loading overlay
function hideLoading() {
    $('#loadingOverlay').removeClass('d-flex').addClass('d-none');
}

// Show confirmation dialog
function showClearFormConfirmation() {
    Swal.fire({
        title: '<i class="fas fa-exclamation-triangle text-warning fa-2x"></i>',
        html: '<h4 class="text-dark mb-3">Clear Form?</h4>' +
              '<p class="text-muted">Are you sure you want to clear all fields? This action cannot be undone.</p>',
        showCancelButton: true,
        confirmButtonText: '<i class="fas fa-check mr-2"></i> Yes, Clear All',
        cancelButtonText: '<i class="fas fa-times mr-2"></i> Cancel',
        confirmButtonColor: '#ffc107',
        cancelButtonColor: '#6c757d',
        reverseButtons: true,
        backdrop: 'rgba(0,0,0,0.4)',
        customClass: {
            confirmButton: 'btn btn-warning shadow-sm',
            cancelButton: 'btn btn-secondary shadow-sm'
        }
    }).then((result) => {
        if (result.isConfirmed) {
            clearForm();
            showToast('Form cleared successfully!', 'success', 'fa-trash-restore');
        }
    });
}

function clearForm() {
    $('#supplierSelect').val('');
    $('#invoiceNo').val('');
    $('#purchaseDate').val('<?= date('Y-m-d') ?>');
    $('#purchaseNotes').val('');
    $('#itemsTable tbody').empty();
    $('#total').val('0.00');
    $('#itemCount').val('0');
    $('#itemCountBadge').text('0 items');
    $('#noItemsMessage').show();
    rowCounter = 0;
    calculateTotal();
}

function addRow() {
    rowCounter++;
    let row = `
    <tr id="row-${rowCounter}" class="animate__animated animate__fadeIn" data-row-id="${rowCounter}">
        <td>
            <div class="input-group input-group-sm">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light">
                        <i class="fas fa-pills"></i>
                    </span>
                </div>
                <select name="product_id_${rowCounter}" class="form-control product-select shadow-sm" required>
                    <option value="">-- Select Product --</option>
                    ${products.map(p => `<option value="${p.id}" data-unit="${p.unit || 'unit'}">${p.name} (${p.unit || 'unit'})</option>`).join('')}
                </select>
            </div>
        </td>
        <td>
            <input type="text" name="batch_no_${rowCounter}" class="form-control form-control-sm shadow-sm batch-no" required 
                   placeholder="BATCH-001">
        </td>
        <td>
            <input type="number" name="qty_${rowCounter}" class="form-control form-control-sm shadow-sm qty" min="1" required 
                   onchange="calculateTotal()" onkeyup="calculateTotal()">
        </td>
        <td>
            <div class="input-group input-group-sm">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light">TSh</span>
                </div>
                <input type="number" name="cost_price_${rowCounter}" class="form-control shadow-sm cost" step="0.01" required 
                       onchange="calculateTotal()" onkeyup="calculateTotal()">
            </div>
        </td>
        <td>
            <div class="input-group input-group-sm">
                <div class="input-group-prepend">
                    <span class="input-group-text bg-light">TSh</span>
                </div>
                <input type="number" name="sell_price_${rowCounter}" class="form-control shadow-sm sell" step="0.01" required>
            </div>
        </td>
        <td>
            <input type="date" name="expiry_date_${rowCounter}" class="form-control form-control-sm shadow-sm expiry">
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm shadow-sm" onclick="removeRow(${rowCounter})" 
                    title="Remove item" style="border-radius: 50%; width: 30px; height: 30px; padding: 0;">
                <i class="fas fa-trash-alt"></i>
            </button>
        </td>
    </tr>`;
    
    $('#itemsTable tbody').append(row);
    $('#noItemsMessage').hide();
    updateItemCount();
}

function removeRow(rowId) {
    $(`#row-${rowId}`).addClass('animate__animated animate__fadeOut');
    setTimeout(() => {
        $(`#row-${rowId}`).remove();
        calculateTotal();
        updateItemCount();
        
        if ($('#itemsTable tbody tr').length === 0) {
            $('#noItemsMessage').show();
        }
    }, 300);
}

function calculateTotal() {
    let total = 0;
    $('#itemsTable tbody tr').each(function() {
        let qty = parseFloat($(this).find('.qty').val()) || 0;
        let cost = parseFloat($(this).find('.cost').val()) || 0;
        total += qty * cost;
    });
    $('#total').val(total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}));
}

function updateItemCount() {
    let count = $('#itemsTable tbody tr').length;
    $('#itemCount').val(count);
    $('#itemCountBadge').text(count + ' item' + (count !== 1 ? 's' : ''));
}

function validateForm() {
    // Validate supplier
    let supplier = $('#supplierSelect').val();
    if (!supplier) {
        showToast('Please select a supplier from the list.', 'warning', 'fa-truck');
        $('#supplierSelect').addClass('is-invalid').focus();
        return false;
    } else {
        $('#supplierSelect').removeClass('is-invalid');
    }
    
    // Validate invoice number
    let invoiceNo = $('#invoiceNo').val().trim();
    if (!invoiceNo) {
        showToast('Please enter a valid invoice number.', 'warning', 'fa-file-invoice');
        $('#invoiceNo').addClass('is-invalid').focus();
        return false;
    } else {
        $('#invoiceNo').removeClass('is-invalid');
    }
    
    // Validate at least one item
    if ($('#itemsTable tbody tr').length === 0) {
        showToast('Please add at least one item to the purchase.', 'warning', 'fa-box-open');
        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 animate__animated animate__shakeX');
            setTimeout(() => $(this).removeClass('animate__animated animate__shakeX'), 1000);
        } else {
            $(this).removeClass('table-warning');
        }
    });
    
    if (!isValid) {
        let message = invalidRows.length === 1 ? 
            `Item #${invalidRows[0]} has incomplete fields.` :
            `Items #${invalidRows.join(', ')} have incomplete fields.`;
        
        showToast(message, 'danger', 'fa-exclamation-circle');
        return false;
    }
    
    return true;
}

function showPreviewModal() {
    if (!validateForm()) return;
    
    let supplier = $('#supplierSelect option:selected').text();
    let invoiceNo = $('#invoiceNo').val();
    let purchaseDate = $('#purchaseDate').val();
    let total = $('#total').val();
    let notes = $('#purchaseNotes').val();
    
    let itemsHTML = '';
    $('#itemsTable tbody tr').each(function(index) {
        let product = $(this).find('.product-select option:selected').text();
        let batch = $(this).find('.batch-no').val();
        let qty = $(this).find('.qty').val();
        let cost = $(this).find('.cost').val();
        let sell = $(this).find('.sell').val();
        let expiry = $(this).find('.expiry').val();
        
        itemsHTML += `
            <tr class="border-bottom">
                <td class="py-2">${index + 1}</td>
                <td class="py-2">${product}</td>
                <td class="py-2">${batch}</td>
                <td class="py-2 text-right">${qty}</td>
                <td class="py-2 text-right">${parseFloat(cost).toFixed(2)}</td>
                <td class="py-2 text-right">${parseFloat(sell).toFixed(2)}</td>
                <td class="py-2">${expiry || 'N/A'}</td>
            </tr>`;
    });
    
    let previewHTML = `
        <div class="preview-container">
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-truck mr-2"></i>Supplier</h6>
                            <h5 class="card-title text-primary">${supplier}</h5>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-file-invoice mr-2"></i>Invoice Details</h6>
                            <p class="card-text mb-1"><strong>Invoice No:</strong> ${invoiceNo}</p>
                            <p class="card-text"><strong>Date:</strong> ${purchaseDate}</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="table-responsive mb-4">
                <table class="table table-bordered">
                    <thead class="thead-light">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Batch No</th>
                            <th class="text-right">Qty</th>
                            <th class="text-right">Cost Price</th>
                            <th class="text-right">Sell Price</th>
                            <th>Expiry</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${itemsHTML}
                    </tbody>
                </table>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-sticky-note mr-2"></i>Notes</h6>
                            <p class="card-text">${notes || 'No notes provided'}</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="card border-0 bg-light shadow-sm">
                        <div class="card-body">
                            <h6 class="card-subtitle mb-2 text-muted"><i class="fas fa-calculator mr-2"></i>Summary</h6>
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0 text-success">Total Amount:</h5>
                                <h3 class="card-title mb-0 text-success">TSh ${total}</h3>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>`;
    
    $('#previewContent').html(previewHTML);
    $('#previewModal').modal('show');
}

function savePurchase() {
    $('#previewModal').modal('hide');
    
    if (!validateForm()) return;
    
    showLoading('Saving Purchase...');
    
    let submitBtn = $('#savePurchaseBtn');
    let originalText = submitBtn.html();
    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i> Saving...');
    
    let formData = collectFormData();
    
    $.ajax({
        url: 'save_purchase.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            hideLoading();
            submitBtn.prop('disabled', false).html(originalText);
            
            if (response.status === 'success') {
                Swal.fire({
                    title: '<i class="fas fa-check-circle text-success fa-3x"></i>',
                    html: '<h4 class="text-dark mt-3 mb-2">Purchase Saved!</h4>' +
                          '<p class="text-muted mb-4">Purchase has been successfully recorded.</p>' +
                          '<div class="alert alert-info text-left">' +
                          `<p class="mb-1"><strong>Invoice:</strong> ${response.invoice_no}</p>` +
                          `<p class="mb-0"><strong>Purchase ID:</strong> ${response.purchase_id}</p>` +
                          '</div>',
                    confirmButtonText: '<i class="fas fa-eye mr-2"></i> View Purchase',
                    confirmButtonColor: '#28a745',
                    showCancelButton: true,
                    cancelButtonText: '<i class="fas fa-plus mr-2"></i> New Purchase',
                    backdrop: 'rgba(0,0,0,0.4)',
                    customClass: {
                        confirmButton: 'btn btn-success shadow-sm px-4',
                        cancelButton: 'btn btn-outline-primary shadow-sm px-4'
                    }
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = 'list_purchases.php?added=1&id=' + response.purchase_id;
                    } else {
                        clearForm();
                        addRow();
                        $('#invoiceNo').val('');
                    }
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: response.message,
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#dc3545'
                });
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            submitBtn.prop('disabled', false).html(originalText);
            
            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 = 'Server Error: ' + xhr.statusText;
                }
            }
            
            Swal.fire({
                icon: 'error',
                title: 'Save Failed!',
                html: `<p class="text-danger">${errorMsg}</p>` +
                      '<p class="text-muted small mt-2">Please check your entries and try again.</p>',
                confirmButtonText: 'OK',
                confirmButtonColor: '#dc3545'
            });
        }
    });
}

function collectFormData() {
    let formData = new FormData();
    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());
    formData.append('notes', $('#purchaseNotes').val().trim());
    
    let productIds = [], batchNos = [], qtys = [], costPrices = [], sellPrices = [], 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());
        expiryDates.push($(this).find('.expiry').val() || '');
    });
    
    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
$(document).ready(function() {
    // Add first row automatically
    setTimeout(() => addRow(), 300);
    
    // Set today's date as default
    $('#purchaseDate').val('<?= date('Y-m-d') ?>');
    
    // 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);
            showToast('Invoice number auto-generated', 'info', 'fa-magic');
        }
    });
    
    // Auto-calculate selling price
    $(document).on('change', '.cost', function() {
        let cost = parseFloat($(this).val()) || 0;
        let sellPriceField = $(this).closest('tr').find('.sell');
        
        if (!sellPriceField.val() || parseFloat(sellPriceField.val()) === 0) {
            let sellPrice = cost * 1.3;
            sellPriceField.val(sellPrice.toFixed(2));
            showToast('Selling price calculated automatically (30% markup)', 'info', 'fa-calculator', 2000);
        }
    });
    
    // Remove invalid class on input
    $(document).on('input', '.is-invalid', function() {
        $(this).removeClass('is-invalid');
    });
    
    // Save button click
    $('#savePurchaseBtn').on('click', savePurchase);
});

// Add custom CSS for toast alerts
const toastCSS = `
<style>
.toast-alert {
    animation: slideInRight 0.3s ease-out;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

.table-hover tbody tr:hover {
    background-color: rgba(0,123,255,0.05);
    transform: translateY(-1px);
    transition: all 0.2s ease;
}

.input-group-text {
    transition: all 0.2s ease;
}

.input-group:focus-within .input-group-text {
    background-color: #e9ecef;
    border-color: #80bdff;
}

.btn-lg {
    padding: 0.75rem 1.5rem;
    font-size: 1.1rem;
    border-radius: 8px;
}

.card {
    border-radius: 12px;
    border: none;
}

.card-header {
    border-radius: 12px 12px 0 0 !important;
}

.bg-gradient-primary {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
}

.bg-gradient-info {
    background: linear-gradient(135deg, #17a2b8 0%, #117a8b 100%);
}

.bg-gradient-success {
    background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);
}

.form-control:focus {
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.15);
    border-color: #80bdff;
}

.badge-pill {
    border-radius: 50rem;
    padding: 0.5em 1em;
}
</style>
`;

$('head').append(toastCSS);
</script>

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