<?php $__env->startSection('title', 'Create New Sale'); ?>

<?php $__env->startSection('actions'); ?>
<a href="<?php echo e(route('sales.index')); ?>" class="btn btn-secondary">
    <i class="fas fa-arrow-left"></i> Back to Sales
</a>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('styles'); ?>
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
        --warning-gradient: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
    }

    .product-row {
        background: #ffffff;
        padding: 20px;
        margin-bottom: 20px;
        border-radius: 12px;
        border-left: 5px solid #667eea;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        transition: all 0.3s ease;
        position: relative;
        border: 1px solid #eef2f7;
    }
    
    .product-row:hover {
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        transform: translateY(-2px);
        border-left-color: #764ba2;
    }
    
    .product-row .row {
        align-items: flex-end;
    }
    
    .totals-section {
        background: linear-gradient(135deg, #f5f7fa 0%, #e9ecf2 100%);
        padding: 30px;
        border-radius: 15px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        margin-top: 30px;
        border: 1px solid #dde2e8;
    }
    
    .installment-details {
        background: linear-gradient(135deg, #fff5e6 0%, #ffe9d4 100%);
        padding: 25px;
        border-radius: 15px;
        border-left: 5px solid #ff9800;
        margin: 25px 0;
        border: 1px solid #ffd8b5;
        box-shadow: 0 5px 20px rgba(255,152,0,0.1);
    }
    
    .badge {
        font-size: 0.9rem;
        padding: 8px 12px;
        border-radius: 50px;
        font-weight: 500;
    }
    
    .form-control, .form-select {
        border: 2px solid #eef2f7;
        border-radius: 10px;
        padding: 12px 15px;
        font-size: 14px;
        transition: all 0.3s;
        background: white;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        outline: none;
    }
    
    .form-control:read-only {
        background-color: #f8fafc;
        border-color: #e2e8f0;
    }
    
    .form-label {
        font-weight: 600;
        color: #2d3748;
        margin-bottom: 8px;
        font-size: 13px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .remove-product {
        position: absolute;
        top: -10px;
        right: -10px;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: #f56565;
        color: white;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 4px 10px rgba(245,101,101,0.3);
        z-index: 10;
    }
    
    .remove-product:hover {
        background: #e53e3e;
        transform: scale(1.1);
    }
    
    .stock-info {
        display: block;
        margin-top: 6px;
        color: #718096;
        font-size: 12px;
        font-weight: 500;
    }
    
    .is-invalid {
        border-color: #f56565 !important;
    }
    
    .is-valid {
        border-color: #48bb78 !important;
    }
    
    .card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 10px 40px rgba(0,0,0,0.08);
        overflow: hidden;
    }
    
    .card-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px 30px;
        border: none;
    }
    
    .card-header h5 {
        margin: 0;
        font-weight: 600;
        font-size: 1.3rem;
    }
    
    .btn {
        padding: 12px 30px;
        border-radius: 50px;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.3s;
        border: none;
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
    }
    
    .btn-secondary {
        background: #f7fafc;
        color: #2d3748;
        border: 2px solid #e2e8f0;
    }
    
    .btn-secondary:hover {
        background: #edf2f7;
        transform: translateY(-2px);
    }
    
    .btn-success {
        background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
        color: #2d3748;
    }
    
    .btn-warning {
        background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
        color: white;
    }
    
    .table {
        margin: 0;
    }
    
    .table th {
        font-weight: 600;
        color: #4a5568;
        font-size: 14px;
        border: none;
        padding: 12px 0;
    }
    
    .table td {
        padding: 8px 0;
        border: none;
    }
    
    .alert {
        border-radius: 12px;
        border: none;
        padding: 15px 20px;
    }
    
    .alert-info {
        background: linear-gradient(135deg, #e6f3ff 0%, #d9edff 100%);
        color: #2c5282;
        border-left: 5px solid #4299e1;
    }
    
    /* Custom Select2 Styling */
    .select2-container--default .select2-selection--single {
        height: 48px;
        border: 2px solid #eef2f7;
        border-radius: 10px;
    }
    
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 44px;
        padding-left: 15px;
    }
    
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 46px;
    }
    
    /* Animation */
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .animated {
        animation: slideIn 0.5s ease-out;
    }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid animated">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-cart-plus fa-2x me-3"></i>
                        <div>
                            <h5 class="mb-0">Create New Sale</h5>
                            <small class="text-white-50">Fill in the details to create a new sale</small>
                        </div>
                    </div>
                </div>
                
                <?php if(session('error')): ?>
                <div class="alert alert-danger m-4">
                    <i class="fas fa-exclamation-circle me-2"></i> <?php echo e(session('error')); ?>

                </div>
                <?php endif; ?>
                
                <?php if($errors->any()): ?>
                <div class="alert alert-danger m-4">
                    <h6 class="mb-2"><i class="fas fa-exclamation-triangle me-2"></i>Please fix the following errors:</h6>
                    <ul class="mb-0">
                        <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <li><?php echo e($error); ?></li>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <div class="card-body p-4">
                    <form id="sale-form" method="POST" action="<?php echo e(route('sales.store')); ?>" autocomplete="off">
                        <?php echo csrf_field(); ?>
                        
                        <!-- Customer Information -->
                        <div class="row g-4 mb-4">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="customer_id" class="form-label">
                                        <i class="fas fa-user me-2 text-primary"></i>Customer <span class="text-danger">*</span>
                                    </label>
                                    <select name="customer_id" id="customer_id" class="form-select select2 <?php $__errorArgs = ['customer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required>
                                        <option value="">-- Select Customer --</option>
                                        <?php $__empty_1 = true; $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                        <option value="<?php echo e($customer->id); ?>" 
                                                data-type="<?php echo e($customer->customer_type); ?>"
                                                data-credit="<?php echo e($customer->credit_limit ?? 0); ?>"
                                                data-balance="<?php echo e($customer->outstanding_balance ?? 0); ?>"
                                                <?php echo e(old('customer_id') == $customer->id ? 'selected' : ''); ?>>
                                            <?php echo e($customer->name); ?> | <?php echo e($customer->phone); ?> | <?php echo e($customer->customer_type == 'installment' ? '🏦 Installment' : '💰 Cash'); ?>

                                            <?php if($customer->outstanding_balance > 0): ?>
                                                | Due: ৳ <?php echo e(number_format($customer->outstanding_balance, 2)); ?>

                                            <?php endif; ?>
                                        </option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                        <option value="">No customers available</option>
                                        <?php endif; ?>
                                    </select>
                                    <?php $__errorArgs = ['customer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="sale_date" class="form-label">
                                        <i class="fas fa-calendar me-2 text-primary"></i>Sale Date <span class="text-danger">*</span>
                                    </label>
                                    <input type="date" name="sale_date" id="sale_date" 
                                           class="form-control <?php $__errorArgs = ['sale_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                           value="<?php echo e(old('sale_date', date('Y-m-d'))); ?>" required>
                                    <?php $__errorArgs = ['sale_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Sale Type & Payment -->
                        <div class="row g-4 mb-4">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="sale_type" class="form-label">
                                        <i class="fas fa-tag me-2 text-primary"></i>Sale Type <span class="text-danger">*</span>
                                    </label>
                                    <select name="sale_type" id="sale_type" class="form-select" required>
                                        <option value="cash" <?php echo e(old('sale_type') == 'cash' ? 'selected' : ''); ?>>💰 Cash Sale</option>
                                        <option value="installment" <?php echo e(old('sale_type') == 'installment' ? 'selected' : ''); ?>>🏦 Installment Sale</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="payment_method" class="form-label">
                                        <i class="fas fa-credit-card me-2 text-primary"></i>Payment Method <span class="text-danger">*</span>
                                    </label>
                                    <select name="payment_method" id="payment_method" class="form-select" required>
                                        <option value="cash">💵 Cash</option>
                                        <option value="card">💳 Card</option>
                                        <option value="bank_transfer">🏦 Bank Transfer</option>
                                        <option value="check">📝 Check</option>
                                        <option value="mobile_banking">📱 Mobile Banking</option>
                                        <option value="others">🔄 Others</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="vat_rate" class="form-label">
                                        <i class="fas fa-percent me-2 text-primary"></i>VAT Rate (%)
                                    </label>
                                    <input type="number" name="vat_rate" id="vat_rate" 
                                           class="form-control" step="0.01" min="0" max="100"
                                           value="<?php echo e(old('vat_rate', $defaultSettings['default_vat_rate'] ?? 15)); ?>">
                                </div>
                            </div>
                        </div>
                        
                        <!-- Installment Details -->
                        <div id="installment-section" class="installment-details" style="<?php echo e(old('sale_type') == 'installment' ? 'display: block;' : 'display: none;'); ?>">
                            <h5 class="mb-4"><i class="fas fa-calendar-alt me-2 text-warning"></i>Installment Details</h5>
                            <div class="row g-4">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="down_payment" class="form-label">
                                            <i class="fas fa-money-bill me-2 text-warning"></i>Down Payment (৳) <span class="text-danger">*</span>
                                        </label>
                                        <input type="number" name="down_payment" id="down_payment" 
                                               class="form-control calculate-installment" 
                                               step="0.01" min="0" value="<?php echo e(old('down_payment', 0)); ?>">
                                        <small class="text-muted mt-1 d-block">
                                            <i class="fas fa-info-circle me-1"></i>Minimum: <span id="min-down-payment">0</span> ৳
                                        </small>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="installment_months" class="form-label">
                                            <i class="fas fa-clock me-2 text-warning"></i>Installment Months <span class="text-danger">*</span>
                                        </label>
                                        <select name="installment_months" id="installment_months" 
                                                class="form-select calculate-installment">
                                            <option value="">-- Select Months --</option>
                                            <?php for($i = 3; $i <= ($defaultSettings['max_installment_months'] ?? 36); $i+=3): ?>
                                            <option value="<?php echo e($i); ?>" <?php echo e(old('installment_months') == $i ? 'selected' : ''); ?>>
                                                <?php echo e($i); ?> Months
                                            </option>
                                            <?php endfor; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="interest_rate" class="form-label">
                                            <i class="fas fa-chart-line me-2 text-warning"></i>Interest Rate (%)
                                        </label>
                                        <input type="number" name="interest_rate" id="interest_rate" 
                                               class="form-control calculate-installment" 
                                               step="0.01" min="0" max="50"
                                               value="<?php echo e(old('interest_rate', $defaultSettings['default_interest_rate'] ?? 5)); ?>">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Installment Summary -->
                            <div class="row mt-4">
                                <div class="col-md-12">
                                    <div class="alert alert-info">
                                        <div class="row g-3">
                                            <div class="col-md-3">
                                                <small class="text-muted d-block">Total Amount</small>
                                                <strong class="fs-5" id="total-amount-display">0.00 ৳</strong>
                                            </div>
                                            <div class="col-md-3">
                                                <small class="text-muted d-block">Down Payment</small>
                                                <strong class="fs-5" id="down-payment-display">0.00 ৳</strong>
                                            </div>
                                            <div class="col-md-3">
                                                <small class="text-muted d-block">Remaining</small>
                                                <strong class="fs-5" id="remaining-amount">0.00 ৳</strong>
                                            </div>
                                            <div class="col-md-3">
                                                <small class="text-muted d-block">Monthly Installment</small>
                                                <strong class="fs-5" id="monthly-installment">0.00 ৳</strong>
                                            </div>
                                        </div>
                                        <div class="row mt-3">
                                            <div class="col-md-6">
                                                <small class="text-muted d-block">Total Payable (with interest)</small>
                                                <strong class="fs-5" id="total-payable">0.00 ৳</strong>
                                            </div>
                                            <div class="col-md-6">
                                                <small class="text-muted d-block">Credit Status</small>
                                                <span id="credit-status" class="badge bg-success mt-1">OK</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Products Section -->
                        <div class="mb-4">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="mb-0"><i class="fas fa-boxes me-2 text-info"></i>Products</h5>
                                <button type="button" id="add-product" class="btn btn-primary btn-sm">
                                    <i class="fas fa-plus me-2"></i>Add Product
                                </button>
                            </div>
                            
                            <div id="products-container">
                                <!-- First product row -->
                                <div class="product-row" id="product-row-0">
                                    <button type="button" class="btn btn-danger btn-sm remove-product" style="display: none;">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    
                                    <div class="row g-3 align-items-end">
                                        <div class="col-md-4">
                                            <div class="mb-2">
                                                <label class="form-label small">Product <span class="text-danger">*</span></label>
                                                <select name="items[0][product_id]" 
                                                        class="form-select product-select form-select-sm" required>
                                                    <option value="">-- Select Product --</option>
                                                    <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                    <option value="<?php echo e($product->id); ?>" 
                                                            data-price="<?php echo e($product->selling_price); ?>"
                                                            data-stock="<?php echo e($product->stock_quantity); ?>"
                                                            data-name="<?php echo e($product->name); ?>"
                                                            data-code="<?php echo e($product->code); ?>">
                                                        <?php echo e($product->name); ?> (<?php echo e($product->code); ?>)
                                                    </option>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                                    <option value="">No products available</option>
                                                    <?php endif; ?>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <div class="mb-2">
                                                <label class="form-label small">Qty <span class="text-danger">*</span></label>
                                                <input type="number" name="items[0][quantity]" 
                                                       class="form-control form-control-sm quantity" 
                                                       min="1" value="1" required>
                                                <small class="stock-info">Stock: <span class="stock-count">0</span></small>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <div class="mb-2">
                                                <label class="form-label small">Price</label>
                                                <input type="number" name="items[0][unit_price]" 
                                                       class="form-control form-control-sm price" 
                                                       step="0.01" readonly>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <div class="mb-2">
                                                <label class="form-label small">Total</label>
                                                <input type="number" name="items[0][total]" 
                                                       class="form-control form-control-sm item-total" 
                                                       step="0.01" readonly>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <?php if($products->isEmpty()): ?>
                            <div class="alert alert-warning mt-3">
                                <i class="fas fa-exclamation-triangle me-2"></i> No products available. 
                                <a href="<?php echo e(route('products.create')); ?>" class="alert-link">Add products first</a>.
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Totals Section -->
                        <div class="totals-section">
                            <div class="row">
                                <div class="col-md-7">
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">
                                            <i class="fas fa-sticky-note me-2 text-primary"></i>Notes
                                        </label>
                                        <textarea name="notes" id="notes" class="form-control" rows="4" 
                                                  placeholder="Add any notes about this sale..."><?php echo e(old('notes')); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-5">
                                    <div class="bg-white p-4 rounded-3 shadow-sm">
                                        <h6 class="mb-3 text-primary"><i class="fas fa-calculator me-2"></i>Order Summary</h6>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Subtotal:</span>
                                            <span class="fw-bold" id="subtotal">0.00 ৳</span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">Discount:</span>
                                            <span>
                                                <input type="number" name="discount_amount" id="discount_amount" 
                                                       class="form-control form-control-sm text-end" 
                                                       step="0.01" value="<?php echo e(old('discount_amount', 0)); ?>" min="0"
                                                       style="width: 120px; display: inline-block;">
                                            </span>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mb-2">
                                            <span class="text-muted">VAT (<span id="vat-rate-display"><?php echo e(old('vat_rate', $defaultSettings['default_vat_rate'] ?? 15)); ?></span>%):</span>
                                            <span class="fw-bold" id="vat-amount">0.00 ৳</span>
                                        </div>
                                        
                                        <hr class="my-3">
                                        
                                        <div class="d-flex justify-content-between">
                                            <span class="h5 mb-0">Grand Total:</span>
                                            <span class="h5 mb-0 text-primary" id="grand-total">0.00 ৳</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Submit Buttons -->
                        <div class="text-center mt-5">
                            <button type="submit" class="btn btn-primary btn-lg px-5 me-3">
                                <i class="fas fa-save me-2"></i>Create Sale
                            </button>
                            <button type="button" id="reset-form" class="btn btn-secondary btn-lg px-5">
                                <i class="fas fa-redo me-2"></i>Reset
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    let productRowCount = 1;
    
    // Check if jQuery is loaded
    console.log('jQuery version:', $.fn.jquery);
    
    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({
            width: '100%',
            placeholder: 'Select Customer',
            theme: 'bootstrap-5'
        });
        console.log('Select2 initialized');
    } else {
        console.error('Select2 not loaded');
    }
    
    // Debug: Check if data is loaded
    console.log('Products loaded:', <?php echo json_encode($products, 15, 512) ?>);
    console.log('Customers loaded:', <?php echo json_encode($customers, 15, 512) ?>);
    
    // ============ PRODUCT SELECTION HANDLER ============
    $(document).on('change', '.product-select', function() {
        console.log('Product select changed');
        let selectedOption = $(this).find('option:selected');
        let row = $(this).closest('.product-row');
        let productId = $(this).val();
        
        console.log('Selected product ID:', productId);
        
        if (productId && productId !== '') {
            let price = parseFloat(selectedOption.data('price')) || 0;
            let stock = parseInt(selectedOption.data('stock')) || 0;
            let productName = selectedOption.data('name') || '';
            
            console.log('Product selected - Price:', price, 'Stock:', stock, 'Name:', productName);
            
            // Set price
            row.find('.price').val(price.toFixed(2));
            
            // Set stock info
            row.find('.stock-count').text(stock);
            
            // Enable quantity input and set max
            let qtyInput = row.find('.quantity');
            qtyInput.attr('max', stock);
            qtyInput.prop('readonly', false);
            
            // Calculate total
            calculateRowTotal(row);
            calculateGrandTotal();
        } else {
            // Clear fields if no product selected
            row.find('.price').val('');
            row.find('.stock-count').text('0');
            row.find('.item-total').val('');
            row.find('.quantity').val(1);
        }
    });
    
    // ============ QUANTITY CHANGE HANDLER ============
    $(document).on('input', '.quantity', function() {
        console.log('Quantity changed');
        let row = $(this).closest('.product-row');
        let productSelect = row.find('.product-select');
        let productId = productSelect.val();
        
        console.log('Product ID:', productId);
        
        if (!productId || productId === '') {
            Swal.fire({
                icon: 'warning',
                title: 'Warning',
                text: 'Please select a product first',
                timer: 2000,
                showConfirmButton: false
            });
            $(this).val(1);
            return;
        }
        
        let selectedOption = productSelect.find('option:selected');
        let stock = parseInt(selectedOption.data('stock')) || 0;
        let quantity = parseInt($(this).val()) || 1;
        
        console.log('Quantity:', quantity, 'Stock:', stock);
        
        // Validate quantity
        if (quantity < 1) {
            $(this).val(1);
            quantity = 1;
        }
        
        if (quantity > stock) {
            Swal.fire({
                icon: 'warning',
                title: 'Stock Limit',
                text: 'Only ' + stock + ' items available in stock',
                timer: 2000,
                showConfirmButton: false
            });
            $(this).val(stock);
            quantity = stock;
        }
        
        // Calculate row total
        calculateRowTotal(row);
        calculateGrandTotal();
    });
    
    // ============ DISCOUNT/VAT CHANGE HANDLER ============
    $(document).on('input', '#discount_amount, #vat_rate', function() {
        console.log('Discount/VAT changed');
        calculateGrandTotal();
    });
    
    // ============ INSTALLMENT CALCULATION ============
    $(document).on('input', '.calculate-installment', function() {
        console.log('Installment calculation triggered');
        calculateInstallment();
    });
    
    // ============ ADD NEW PRODUCT ROW ============
    $('#add-product').click(function() {
        console.log('Add product clicked');
        addNewProductRow();
    });
    
    // ============ REMOVE PRODUCT ROW ============
    $(document).on('click', '.remove-product', function() {
        console.log('Remove product clicked');
        if ($('.product-row').length > 1) {
            let row = $(this).closest('.product-row');
            row.fadeOut(300, function() {
                $(this).remove();
                calculateGrandTotal();
            });
        } else {
            Swal.fire({
                icon: 'warning',
                title: 'Cannot Remove',
                text: 'You need at least one product',
                timer: 2000,
                showConfirmButton: false
            });
        }
    });
    
    // ============ SALE TYPE TOGGLE ============
    $('#sale_type').change(function() {
        let saleType = $(this).val();
        console.log('Sale type changed to:', saleType);
        
        if (saleType === 'installment') {
            $('#installment-section').slideDown(300);
            $('#down_payment, #installment_months').prop('required', true);
        } else {
            $('#installment-section').slideUp(300);
            $('#down_payment, #installment_months').prop('required', false).removeAttr('required');
        }
        calculateGrandTotal();
    });
    
    // ============ CUSTOMER SELECTION ============
    $('#customer_id').change(function() {
        let selectedOption = $(this).find('option:selected');
        let customerType = selectedOption.data('type');
        console.log('Customer selected, type:', customerType);
        
        if (customerType === 'installment') {
            $('#sale_type').val('installment').trigger('change');
        }
    });
    
    // ============ FUNCTION: Calculate Row Total ============
    function calculateRowTotal(row) {
        let quantity = parseFloat(row.find('.quantity').val()) || 0;
        let price = parseFloat(row.find('.price').val()) || 0;
        let total = quantity * price;
        
        console.log('Row total - Qty:', quantity, 'Price:', price, 'Total:', total);
        
        row.find('.item-total').val(total.toFixed(2));
        return total;
    }
    
    // ============ FUNCTION: Calculate Grand Total ============
    function calculateGrandTotal() {
        console.log('Calculating grand total...');
        
        let subtotal = 0;
        $('.item-total').each(function() {
            let val = parseFloat($(this).val()) || 0;
            subtotal += val;
        });
        
        let discount = parseFloat($('#discount_amount').val()) || 0;
        let vatRate = parseFloat($('#vat_rate').val()) || 0;
        
        let afterDiscount = Math.max(subtotal - discount, 0);
        let vatAmount = afterDiscount * (vatRate / 100);
        let grandTotal = afterDiscount + vatAmount;
        
        console.log('Subtotal:', subtotal, 'Discount:', discount, 'VAT:', vatAmount, 'Grand Total:', grandTotal);
        
        $('#subtotal').text(subtotal.toFixed(2) + ' ৳');
        $('#vat-amount').text(vatAmount.toFixed(2) + ' ৳');
        $('#vat-rate-display').text(vatRate);
        $('#grand-total').text(grandTotal.toFixed(2) + ' ৳');
        $('#total-amount-display').text(grandTotal.toFixed(2) + ' ৳');
        
        calculateInstallment(grandTotal);
    }
    
    // ============ FUNCTION: Calculate Installment ============
    function calculateInstallment(total = null) {
        if ($('#sale_type').val() !== 'installment') return;
        
        if (!total) {
            total = parseFloat($('#grand-total').text()) || 0;
        }
        
        let downPayment = parseFloat($('#down_payment').val()) || 0;
        let months = parseInt($('#installment_months').val()) || 1;
        let interestRate = parseFloat($('#interest_rate').val()) || 0;
        
        // Minimum down payment validation
        let minDownPaymentPercent = <?php echo e($defaultSettings['minimum_down_payment'] ?? 20); ?>;
        let minDownPayment = total * (minDownPaymentPercent / 100);
        $('#min-down-payment').text(minDownPayment.toFixed(2));
        
        if (downPayment < minDownPayment && downPayment > 0) {
            $('#down_payment').addClass('is-invalid').removeClass('is-valid');
            $('#credit-status').removeClass('bg-success').addClass('bg-warning').text('Low Down Payment');
        } else if (downPayment > 0) {
            $('#down_payment').removeClass('is-invalid').addClass('is-valid');
            $('#credit-status').removeClass('bg-warning').addClass('bg-success').text('OK');
        }
        
        // Calculate monthly installment
        let remaining = total - downPayment;
        if (remaining < 0) remaining = 0;
        
        if (interestRate > 0 && remaining > 0) {
            remaining = remaining * (1 + (interestRate / 100));
        }
        
        let monthly = months > 0 ? remaining / months : 0;
        
        // Update display
        $('#down-payment-display').text(downPayment.toFixed(2) + ' ৳');
        $('#remaining-amount').text((total - downPayment).toFixed(2) + ' ৳');
        $('#monthly-installment').text(monthly.toFixed(2) + ' ৳');
        $('#total-payable').text((downPayment + remaining).toFixed(2) + ' ৳');
        
        console.log('Installment calc - Down:', downPayment, 'Monthly:', monthly, 'Total Payable:', downPayment + remaining);
    }
    
    // ============ FUNCTION: Add New Product Row ============
    function addNewProductRow() {
        let template = $('#product-row-0').clone();
        let newId = 'product-row-' + productRowCount;
        
        template.attr('id', newId);
        template.find('.remove-product').show();
        
        // Update input names
        template.find('select, input').each(function() {
            let name = $(this).attr('name');
            if (name) {
                let newName = name.replace('[0]', '[' + productRowCount + ']');
                $(this).attr('name', newName);
            }
            $(this).val('');
        });
        
        // Reset values
        template.find('.product-select').val('');
        template.find('.quantity').val(1);
        template.find('.price').val('');
        template.find('.item-total').val('');
        template.find('.stock-count').text('0');
        
        // Add to container
        $('#products-container').append(template.hide().fadeIn(300));
        productRowCount++;
        console.log('New row added. Total rows:', productRowCount);
    }
    
    // ============ FORM SUBMIT HANDLER ============
    $('#sale-form').submit(function(e) {
        console.log('Form submitting...');
        
        let errors = [];
        
        // Validate customer
        if (!$('#customer_id').val()) {
            errors.push('Please select a customer.');
        }
        
        // Validate products
        let hasProduct = false;
        let productErrors = [];
        
        $('.product-row').each(function(index) {
            let productSelect = $(this).find('.product-select');
            let quantity = $(this).find('.quantity').val();
            
            if (productSelect.val() && productSelect.val() !== '') {
                hasProduct = true;
                
                // Check stock
                let selectedOption = productSelect.find('option:selected');
                let stock = parseInt(selectedOption.data('stock')) || 0;
                if (parseInt(quantity) > stock) {
                    productErrors.push('Product ' + (index + 1) + ': Only ' + stock + ' items available');
                }
            }
        });
        
        if (!hasProduct) {
            errors.push('Please add at least one product.');
        }
        
        // Add product errors to main errors
        errors = errors.concat(productErrors);
        
        // Validate installment
        if ($('#sale_type').val() === 'installment') {
            let total = parseFloat($('#grand-total').text()) || 0;
            let downPayment = parseFloat($('#down_payment').val()) || 0;
            
            if (downPayment <= 0) {
                errors.push('Down payment is required for installment sales');
            }
            
            if (!$('#installment_months').val()) {
                errors.push('Installment months is required');
            }
        }
        
        // Show errors if any
        if (errors.length > 0) {
            e.preventDefault();
            console.log('Validation errors:', errors);
            
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                html: errors.join('<br>'),
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // Disable submit button
        $(this).find('button[type="submit"]')
            .prop('disabled', true)
            .html('<i class="fas fa-spinner fa-spin me-2"></i>Processing...');
        
        return true;
    });
    
    // ============ RESET FORM ============
    $('#reset-form').click(function() {
        Swal.fire({
            title: 'Reset Form?',
            text: 'All entered data will be lost!',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, reset it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('#sale-form')[0].reset();
                $('#sale_type').trigger('change');
                
                // Remove extra rows
                $('.product-row:not(#product-row-0)').remove();
                
                // Reset first row
                let firstRow = $('#product-row-0');
                firstRow.find('.product-select').val('').trigger('change');
                firstRow.find('.quantity').val(1);
                firstRow.find('.price').val('');
                firstRow.find('.item-total').val('');
                firstRow.find('.stock-count').text('0');
                
                calculateGrandTotal();
                productRowCount = 1;
                
                Swal.fire('Reset!', 'Form has been reset.', 'success');
            }
        });
    });
    
    // ============ INITIAL SETUP ============
    // Trigger initial calculations
    $('#sale_type').trigger('change');
    calculateGrandTotal();
    
    // Set min date for sale date
    let today = new Date().toISOString().split('T')[0];
    $('#sale_date').attr('min', today);
    
    console.log('Document ready - Initialization complete');
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/naowarin/walton.naowarinternational.my.id/resources/views/sales/create.blade.php ENDPATH**/ ?>