
<?php $__env->startPush('style'); ?>
    <style>
        /* Style for the search results dropdown */
        #customer_results {
            position: absolute;
            z-index: 1000;
            /* Ensure it appears above other elements */
            background-color: #fff;
            border: 1px solid #ccc;
            border-top: none;
            max-height: 200px;
            overflow-y: auto;
            width: 100%;
            /* Match the width of the input field */
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        /* Style for individual search items */
        .search-item {
            padding: 8px 12px;
            cursor: pointer;
            list-style-type: none;
            /* Remove bullet points */
        }

        .search-item:hover {
            background-color: #f8f9fa;
            /* Highlight on hover */
        }

        /* Hide the dropdown by default */
        #customer_results {
            display: none;
        }
    </style>
<?php $__env->stopPush(); ?>
<?php $__env->startSection('main'); ?>
    
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Direct Sell</h1>
                </div>

            </div>
        </div><!-- /.container-fluid -->
        
        <?php if(session('success')): ?>
            <!-- Alert hidden - global notification handler will show notification -->
            <div class="alert alert-success" style="display: none;">
                <?php echo e(session('success')); ?>

            </div>
            <script>
                // Override global notification and add sound for direct sales
                document.addEventListener('DOMContentLoaded', function() {
                    // Wait a bit for notification system to initialize
                    setTimeout(function() {
                        // Play success sound
                        if (typeof playSound === 'function') {
                            console.log('Playing success sound for direct sale');
                            playSound('success');
                        }
                        
                        // The global handler will show the notification, we just add sound
                        console.log('Direct sale success sound triggered');
                    }, 1500);
                });
            </script>
            
        <?php endif; ?>

        <?php if(session('error')): ?>
            <!-- Alert hidden - global notification handler will show notification -->
            <div class="alert alert-danger" style="display: none;">
                <?php echo e(session('error')); ?>

            </div>
            <script>
                // Add sound for error messages (global handler shows notification)
                document.addEventListener('DOMContentLoaded', function() {
                    // Wait a bit for notification system to initialize
                    setTimeout(function() {
                        // Play error sound
                        if (typeof playSound === 'function') {
                            console.log('Playing error sound for direct sale');
                            playSound('cancel');
                        }
                        
                        // The global handler will show the notification, we just add sound
                        console.log('Direct sale error sound triggered');
                    }, 1500);
                });
            </script>
        <?php endif; ?>

        <?php if($errors->any()): ?>
            <!-- Hidden alert for fallback -->
            <div class="alert alert-danger" style="display: none;">
                <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>
            <script>
                // Add sound for validation errors
                document.addEventListener('DOMContentLoaded', function() {
                    // Wait a bit for notification system to initialize
                    setTimeout(function() {
                        // Play error sound
                        if (typeof playSound === 'function') {
                            console.log('Playing validation error sound');
                            playSound('cancel');
                        }
                        
                        // Show single validation notification
                        if (typeof window.notificationSystem !== 'undefined') {
                            window.notificationSystem.show({
                                type: 'error',
                                title: 'Validation Error!',
                                message: 'Please check the form fields and try again.',
                                duration: 5000
                            });
                        } else {
                            // Fallback: show the alert if notification system not available
                            document.querySelector('.alert-danger').style.display = 'block';
                        }
                    }, 1500);
                });
            </script>
        <?php endif; ?>

        
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">General</h3>

                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip"
                                title="Collapse">
                                <i class="fas fa-minus"></i></button>
                        </div>
                    </div>
                    <form method="POST" action="<?php echo e(route('direct-sales.store')); ?>">
                        <?php echo csrf_field(); ?>
                        <!-- Customer Info -->
                        <div class="card-body">
                            <div class="row">
                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="customer_search">Search Customer:</label>
                                        <input type="text" class="form-control" id="customer_search"
                                            placeholder="Search by name or mobile..." autocomplete="off">
                                        <input type="hidden" id="customer_name" name="customer_name" readonly>
                                        <div id="customer_results" class="search-results"></div>
                                        <!-- Dropdown for results -->

                                        <button type="button" data-toggle="modal" data-target="#modal-add-customer"
                                            class="btn btn-block">
                                            <i class="fas fa-plus"></i> Add New Customer
                                        </button>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="gb">Product Type:</label>
                                        <select id="product_type" class="form-control" name="product_type" required="">
                                            <option value="">-- Select Product Type --</option>
                                            <option value="Phone">Phone</option>
                                            <option value="Tab">Tab</option>
                                            <option value="Computer">Computer</option>
                                            <option value="Accessories">Accessories</option>
                                            <option value="Repair">Repair</option>
                                            <option value="Others">Others</option>
                                            <option value="Custom">Custom (Type Your Own)</option>
                                        </select>
                                        
                                        <!-- Custom Product Type Input - Hidden by default -->
                                        <div id="custom_product_type_container" style="display: none; margin-top: 10px;">
                                            <label for="custom_product_type">Enter Custom Product Type:</label>
                                            <input type="text" class="form-control" id="custom_product_type" 
                                                   name="custom_product_type" placeholder="Type your custom product type...">
                                        </div>
                                        
                                        <!-- Hidden field to store the actual product type value -->
                                        <input type="hidden" id="actual_product_type" name="actual_product_type">
                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="purchase_note">Purchase Note:</label>
                                        <input type="text" class="form-control" id="purchase_note" name="purchase_note">
                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="sell_price">Sell Price:</label>
                                        <input type="number" class="form-control" step="0.01" id="sell_price"
                                            name="sell_price" required>
                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="cost_price">Cost Price:</label>
                                        <input type="number" class="form-control" step="0.01" id="cost_price"
                                            name="cost_price" required>
                                    </div>
                                </div>

                                <div class="col-6">
                                    <div class="form-group">
                                        <label for="qty">Quantity:</label>
                                        <input type="number" class="form-control" value="1" id="qty"
                                            name="qty" required>
                                    </div>
                                </div>

                                <div class="col-12  text-center">
                                    <button type="submit" class="btn btn-block bg-gradient-primary">
                                        Submit Sale
                                    </button>
                                </div>
                            </div>
                            <div class="col-6">

                            <!-- Popup will display here after successful form submission -->
                    </form>
                </div>


            </div>
            <!-- /.card -->
        </div>

    </section>

    
    <div class="modal fade" id="modal-add-customer">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Add New Customer</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        
                    </button>
                </div>
                <form id="customer_form">
                    <?php echo csrf_field(); ?> <!-- CSRF Token -->
                    <div class="modal-body">
                        <label for="customer_name">Customer Name:</label>
                        <input type="text" id="customer_name" class="form-control" name="customer_name" required>

                        <label for="customer_number">Customer Number:</label>
                        <input type="tel" id="customer_number" class="form-control" name="customer_number" required>

                        <label for="customer_cpr">Customer CPR:</label>
                        <input type="text" id="customer_cpr" class="form-control" name="customer_cpr">

                        <label for="address">Address:</label>
                        <input type="text" id="address" class="form-control" name="address">

                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Customer</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    

    <!-- Audio elements for sound effects -->
    <audio id="foundSound" preload="auto">
        <source src="data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBzuR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxQp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LD..." type="audio/wav">
    </audio>
    <audio id="successSound" preload="auto">
        <source src="data:audio/wav;base64,UklGRpIGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YW4GAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBzuR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2+LDciUFLYDO8tiJNwgYaLvt55c=" type="audio/wav">
    </audio>
    <audio id="cancelSound" preload="auto">
        <source src="data:audio/wav;base64,UklGRtYGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YbIGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBzuR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt559NEAxPp+PwtmMcBzqR0fPAayIGAj6a2/LDciUFLYDO8tiJNwgYaLvt55c=" type="audio/wav">
    </audio>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('script'); ?>
    <script>
        $(document).ready(function() {


            // +++++++++++++++++++++++++   ( 2 )    ++++++++++++++++++++++++++++++++++++++++
            $('#customer_form').on('submit', function(e) {
                e.preventDefault(); // Prevent default form submission

                $.ajax({
                    url: "<?php echo e(route('customer.store')); ?>",
                    type: "POST",
                    data: $(this).serialize(),
                    success: function(response, status, xhr) {
                        if (xhr.status === 201) { // HTTP 201 Created
                            $('#customer_form')[0].reset(); // Reset the form
                            $('#modal-add-customer').modal('hide'); // Hide modal
                            
                            // Play success sound
                            if (typeof playSound === 'function') {
                                playSound('success');
                            }
                            
                            // Show enhanced notification
                            if (typeof window.notificationSystem !== 'undefined') {
                                window.notificationSystem.show({
                                    type: 'success',
                                    title: 'Customer Added!',
                                    message: response.message || 'Customer added successfully!',
                                    duration: 3000
                                });
                            } else {
                                alert(response.message);
                            }
                        } else {
                            console.log("Unexpected response status: " + xhr.status);
                        }
                    },
                    error: function(xhr) {
                        // Play error sound
                        if (typeof playSound === 'function') {
                            playSound('cancel');
                        }
                        
                        let errorMessage = 'An error occurred';
                        if (xhr.status === 422) { // Validation error
                            let errors = xhr.responseJSON.errors;
                            errorMessage = Object.values(errors).flat().join(", ");
                        } else if (xhr.status === 500) { // Server error
                            errorMessage = "Server Error! Please try again.";
                        } else {
                            errorMessage = "An error occurred. Status: " + xhr.status;
                        }
                        
                        // Show enhanced notification
                        if (typeof window.notificationSystem !== 'undefined') {
                            window.notificationSystem.show({
                                type: 'error',
                                title: 'Customer Creation Failed!',
                                message: errorMessage,
                                duration: 5000
                            });
                        } else {
                            alert(errorMessage);
                        }
                        console.log(xhr.responseText);
                    }
                });
            });
            // +++++++++++++++++++++++++   ( 2 )    ++++++++++++++++++++++++++++++++++++++++


            // +++++++++++++++++++++++++   ( 1 )    ++++++++++++++++++++++++++++++++++++++++
            $("#customer_search").on("keyup", function() {
                let query = $(this).val().trim();
                if (query.length < 2) {
                    $("#customer_results").html("").hide(); // Hide if query is too short
                    return;
                }

                $.ajax({
                    url: "<?php echo e(route('api.customers.search')); ?>",
                    type: "GET",
                    data: {
                        query: query
                    },
                    success: function(response) {
                        let resultHTML = "";
                        if (response.length > 0) {
                            // Play found sound when customers are found
                            if (typeof playSound === 'function') {
                                playSound('found');
                            }
                            
                            resultHTML += '<ul class="">';
                            $.each(response, function(index, customer) {
                                resultHTML += `<li class=" search-item" data-id="${customer.id}" data-name="${customer.name}" data-number="${customer.number}">
                            <strong>${customer.name}</strong> - ${customer.number}
                        </li>`;
                            });
                            resultHTML += '</ul>';
                        } else {
                            resultHTML =
                                '<p class="dropdown-item text-muted">No results found</p>';
                        }

                        $("#customer_results").html(resultHTML).show(); // Show results
                    }
                });
            });

            // Handle selection
            $(document).on("click", ".search-item", function() {
                let customerId = $(this).data("id");
                let customerName = $(this).data("name");
                let customerNumber = $(this).data("number");

                $("#customer_search").val(`${customerName} (${customerNumber})`);
                $("#customer_name").val(customerId); // Store customer ID
                $("#customer_results").hide(); // Hide dropdown after selection
                
                // Play success sound when customer is selected
                if (typeof playSound === 'function') {
                    playSound('success');
                }
                
                // Show notification for customer selection
                if (typeof window.notificationSystem !== 'undefined') {
                    window.notificationSystem.show({
                        type: 'info',
                        title: 'Customer Selected',
                        message: `${customerName} selected for direct sale`,
                        duration: 2000
                    });
                }
            });

            // Hide dropdown on clicking outside
            $(document).on("click", function(e) {
                if (!$(e.target).closest("#customer_search, #customer_results").length) {
                    $("#customer_results").hide();
                }
            });

            // Handle product type change
            $('#product_type').on('change', function() {
                let selectedType = $(this).val();
                
                // Show/hide custom product type input
                if (selectedType === 'Custom') {
                    $('#custom_product_type_container').show();
                    $('#custom_product_type').prop('required', true);
                    
                    // Play found sound for custom selection
                    if (typeof playSound === 'function') {
                        playSound('found');
                    }
                    
                    // Show notification
                    if (typeof window.notificationSystem !== 'undefined') {
                        window.notificationSystem.show({
                            type: 'info',
                            title: 'Custom Product Type',
                            message: 'Please enter your custom product type name',
                            duration: 3000
                        });
                    }
                } else {
                    $('#custom_product_type_container').hide();
                    $('#custom_product_type').prop('required', false).val('');
                }
            });



            // Handle form submission - update actual product type
            $('form').on('submit', function(e) {
                let productType = $('#product_type').val();
                let customProductType = $('#custom_product_type').val();
                
                // Set the actual product type value
                if (productType === 'Custom') {
                    if (customProductType.trim() === '') {
                        e.preventDefault(); // Stop form submission
                        
                        // Play error sound
                        if (typeof playSound === 'function') {
                            playSound('cancel');
                        }
                        
                        // Show error notification
                        if (typeof window.notificationSystem !== 'undefined') {
                            window.notificationSystem.show({
                                type: 'error',
                                title: 'Custom Product Type Required!',
                                message: 'Please enter a custom product type name before submitting.',
                                duration: 4000
                            });
                        } else {
                            alert('Please enter a custom product type name before submitting.');
                        }
                        return false;
                    }
                    $('#actual_product_type').val(customProductType.trim());
                } else {
                    $('#actual_product_type').val(productType);
                }
                
                // Form can proceed
                return true;
            });
            // +++++++++++++++++++++++++   ( 1 )    ++++++++++++++++++++++++++++++++++++++++
        });
        $(document).ready(function () {
    $('#credit_sale').change(function () {
        let customerId = $('#customer_name').val();
        let creditSale = $(this).val();

        if (creditSale == '1' && customerId) {
            $.ajax({
                url: "<?php echo e(route('customer.show', ':id')); ?>".replace(':id', customerId),
                type: "GET",
                success: function (response) {
                    if (response.success) {
                        $('#credit_balance').val(response.customer.credit_balance);
                    }
                },
                error: function (xhr, status, error) {
                    alert("Error fetching customer credit balance.");
                }
            });
        }
    });
});

        // Make playSound globally accessible for direct sales
        window.playSound = function(type) {
            try {
                let audio;
                switch(type) {
                    case 'success':
                        audio = document.getElementById('successSound');
                        break;
                    case 'found':
                        audio = document.getElementById('foundSound');
                        break;
                    case 'cancel':
                        audio = document.getElementById('cancelSound');
                        break;
                    default:
                        console.log('Unknown sound type:', type);
                        return;
                }
                
                if (audio) {
                    console.log('Playing sound:', type); // Debug log
                    audio.currentTime = 0;
                    audio.volume = 0.5; // Set volume to 50%
                    
                    // Try to play the sound
                    const playPromise = audio.play();
                    if (playPromise !== undefined) {
                        playPromise
                            .then(() => {
                                console.log('Sound played successfully:', type);
                            })
                            .catch(e => {
                                console.log('Sound play failed:', type, e);
                                // Enable audio context on user interaction
                                document.addEventListener('click', function enableAudio() {
                                    audio.play().catch(e => console.log('Retry failed:', e));
                                    document.removeEventListener('click', enableAudio);
                                }, { once: true });
                            });
                    }
                } else {
                    console.log('Audio element not found for type:', type);
                }
            } catch (error) {
                console.log('playSound error:', error);
            }
        };

        // Initialize audio elements when page loads
        document.addEventListener('DOMContentLoaded', function() {
            // Preload audio elements
            const audioElements = ['successSound', 'foundSound', 'cancelSound'];
            audioElements.forEach(id => {
                const audio = document.getElementById(id);
                if (audio) {
                    audio.load();
                    console.log('Audio element loaded:', id);
                } else {
                    console.log('Audio element not found:', id);
                }
            });
        });

    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\pos v24.4\resources\views/direct_sell/create.blade.php ENDPATH**/ ?>