

<?php $__env->startSection('title','Requirement'); ?>

<?php $__env->startSection("content"); ?>

<style>
.btn-sm {
    padding: 0.5rem 1.25rem;
    border-radius: 0.5rem;
    font-weight: 600;
    font-size: 0.875rem;
    transition: all 0.2s;
    box-shadow: var(--shadow-sm);
}

.card-body {
    background: white;
    border-radius: 15px;
    padding: 40px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

/* Searchable Dropdown Styles */
.select-wrapper {
    position: relative;
}

.select-search-input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e9ecef;;
    border-color:rgb(233, 236, 239);
    border-radius: 12px;
    font-size: 15px;
}

.select-search-input:focus {
    border-color: #86b7fe;
    outline: 0;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.select-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    max-height: 200px;
    overflow-y: auto;
    background: white;
    border: 1px solid #ced4da;
    border-top: none;
    border-radius: 0 0 0.25rem 0.25rem;
    z-index: 1000;
    display: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.select-dropdown.show {
    display: block;
}

.select-option {
    padding: 0.5rem 0.75rem;
    cursor: pointer;
    transition: background-color 0.2s;
}

.select-option:hover {
    background-color: #f8f9fa;
}

.select-option.selected {
    background-color: #0d6efd;
    color: white;
}

.no-results {
    padding: 0.5rem 0.75rem;
    color: #6c757d;
    text-align: center;
}
/* SELECT2 ko State/City jaisa dikhane ke liye */
.select2-container {
    width: 100% !important;
}

.select2-container--default .select2-selection--single {
    height: 48px !important;
    padding: 10px 14px !important;
    border: 2px solid rgb(233, 236, 239) !important;
    border-radius: 12px !important;
    font-size: 15px !important;
    display: flex !important;
    align-items: center !important;
}

.select2-container--default .select2-selection--single:focus,
.select2-container--default.select2-container--open 
.select2-selection--single {
    border-color: #86b7fe !important;
    box-shadow: 0 0 0 0.25rem rgba(13,110,253,.25) !important;
}

.select2-selection__rendered {
    padding-left: 0 !important;
    line-height: normal !important;
}

.select2-selection__arrow {
    height: 100% !important;
    right: 10px !important;
}

</style>

<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">

<div class="container py-5">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Brand Requirement Form</h5>

        <button class="btn all-req-btn"
                data-bs-toggle="modal"
                data-bs-target="#allRequirementsModal">
            All Brand Requirements
        </button>
    </div>

    <div class="card-body">

        <?php if(session('success')): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php echo e(session('success')); ?>

                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <form method="POST" action="/requirements">
            <?php echo csrf_field(); ?>

            <div class="row mb-3 form-group-wrapper">

                <div class="col-lg-2 col-md-4">
                    <label>Brand
                        <span class="required">*</span>
                    </label>
                    <select name="brand_id"
                            id="brand_id"
                            class="form-select select-search-input">
                        <option value="">Select Brand</option>
                        <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($brand->id); ?>">
                                <?php echo e($brand->name); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <div class="col-lg-2 col-md-4">
                    <label>Brand POC
                        <span class="required">*</span>
                    </label>

                    <select name="brand_poc_id"
                            id="brand_poc_id"
                            class="form-select select-search-input" required>
                        <option value="">Select Brand First</option>
                    </select>
                </div>

                <!-- State with Search -->
                <div class="col-lg-2 col-md-4">
                    <label>State
                        <span class="required">*</span>
                    </label>
                    <div class="select-wrapper">
                        <input type="text" 
                               class="select-search-input" 
                               id="state_search" 
                               placeholder="Search State..."
                               autocomplete="off">
                        <input type="hidden" name="state_id" id="state_id" required>
                        <div class="select-dropdown" id="state_dropdown"></div>
                    </div>
                </div>

                <!-- City with Search -->
                <div class="col-lg-2 col-md-6">
                    <label>City
                        <span class="required">*</span>
                    </label>
                    <div class="select-wrapper">
                        <input type="text" 
                               class="select-search-input" 
                               id="city_search" 
                               placeholder="Select State First"
                               autocomplete="off"
                               disabled>
                        <input type="hidden" name="city_id" id="city_id" required>
                        <div class="select-dropdown" id="city_dropdown"></div>
                    </div>
                </div>

                <!-- Market with Search -->
                <div class="col-lg-2 col-md-6">
                    <label>Market
                        <span class="required">*</span>
                    </label>
                    <div class="select-wrapper">
                        <input type="text" 
                               class="select-search-input" 
                               id="market_search" 
                               placeholder="Select City First"
                               autocomplete="off"
                               disabled>
                        <input type="hidden" name="market_id" id="market_id" required>
                        <div class="select-dropdown" id="market_dropdown"></div>
                    </div>
                </div>

            </div>

            <div class="row mb-3 form-group-wrapper">

                <div class="col-md-2">
                    <label>Monthly Budget
                        <span class="required">*</span>
                    </label>
                    <input name="budget" class="form-control" placeholder="1,50,000" required>
                </div>

                <div class="col-md-2">
                    <label>Size Range
                        <span class="required">*</span>
                    </label>
                    <input name="size_range" class="form-control" placeholder="1000 - 1500 Sq Ft" required>
                </div>

                <div class="col-md-2">
                    <label>Type 
                        <span class="required">*</span>
                    </label>
                    <select name="type" class="form-select" required>
                        <option value="">Select Property Type</option>
                        <option>High Street</option>
                        <option>Mall</option>
                    </select>
                </div>

              <div class="col-md-2">
    <label>Floor
        <span class="required">*</span>
    </label>
    <select name="floor_preference" class="form-control" required>
        <option value="">Select Floor</option>
        <option value="LGF">LGF</option>
        <option value="GF">GF</option>
        <option value="FF">FF</option>
        <option value="SF">SF</option>
         <option value="SF">3rd floor</option>
          <option value="SF">4rd floor</option>
    </select>
</div>


               <div class="col-md-2">
    <label>Timeline/Months
        <span class="required">*</span>
    </label>
    <select name="timeline" class="form-control" required>
        <option value="">Select Timeline</option>
        <option value="1 Month">1 Month</option>
        <option value="2 Months">2 Months</option>
        <option value="3 Months">3 Months</option>
        <option value="4 Months">4 Months</option>
        <option value="5 Months">5 Months</option>
        <option value="6 Months">6 Months</option>
        <option value="7 Months">7 Months</option>
        <option value="8 Months">8 Months</option>
        <option value="9 Months">9 Months</option>
        <option value="10 Months">10 Months</option>
        <option value="11 Months">11 Months</option>
        <option value="12 Months">12 Months</option>
    </select>
</div>






                

                <div class="col-md-2">
                    <label>Frontage Required
                        <span class="required">*</span>
                    </label>
                    <input name="footage" class="form-control" placeholder="Enter Frontage" required>
                </div>

            </div>

            <div class="d-grid">
                <button class="btn btn-primary btn-lg btn-req">
                    Save Requirement
                </button>
            </div>

        </form>

    </div>
</div>

<!-- ALL REQUIREMENTS MODAL -->
<div class="modal fade" id="allRequirementsModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">All Brand Requirements</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <table class="table table-bordered table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>SR.No.</th>
                            <th>Brand</th>
                            <th>POC</th>
                            <th>State</th>
                            <th>City</th>
                            <th>Market</th>
                            <th>Budget</th>
                            <th>Type</th>
                            <th width="200">Action</th>
                        </tr>
                    </thead>
                    <tbody id="requirementTable"></tbody>
                </table>
                <div id="requirementPagination" class="mt-3 d-flex justify-content-end"></div>
            </div>

        </div>
    </div>
</div>

<!-- VIEW MODAL -->
<div class="modal fade" id="viewModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">View Requirement</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewContent"></div>
        </div>
    </div>
</div>

<!-- EDIT MODAL -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">Edit Requirement</h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body" id="editContent">
                <!-- AJAX CONTENT -->
            </div>

        </div>
    </div>
</div>

<!-- SEARCHABLE DROPDOWN SCRIPT -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    
    let statesData = [];
    let citiesData = [];
    let marketsData = [];

    // Searchable Dropdown Function
    function initSearchableDropdown(searchInput, dropdown, hiddenInput, data, onSelect) {
        
        searchInput.addEventListener('focus', function() {
            renderOptions(data);
            dropdown.classList.add('show');
        });

        searchInput.addEventListener('input', function() {
            const query = this.value.toLowerCase();
            const filtered = data.filter(item => 
                item.name.toLowerCase().includes(query)
            );
            renderOptions(filtered);
        });

        function renderOptions(items) {
            if (items.length === 0) {
                dropdown.innerHTML = '<div class="no-results">No results found</div>';
                return;
            }

            dropdown.innerHTML = items.map(item => 
                `<div class="select-option" data-id="${item.id}" data-name="${item.name}">
                    ${item.name}
                </div>`
            ).join('');

            dropdown.querySelectorAll('.select-option').forEach(option => {
                option.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const name = this.getAttribute('data-name');
                    
                    searchInput.value = name;
                    hiddenInput.value = id;
                    dropdown.classList.remove('show');
                    
                    if (onSelect) onSelect(id);
                });
            });
        }

        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.classList.remove('show');
            }
        });
    }

    // State Dropdown
    const stateSearch = document.getElementById('state_search');
    const stateDropdown = document.getElementById('state_dropdown');
    const stateHidden = document.getElementById('state_id');

    fetch('/states')
        .then(res => res.json())
        .then(data => {
            statesData = data;
            initSearchableDropdown(stateSearch, stateDropdown, stateHidden, statesData, function(stateId) {
                // Reset city and market
                document.getElementById('city_search').value = '';
                document.getElementById('city_id').value = '';
                document.getElementById('market_search').value = '';
                document.getElementById('market_id').value = '';
                
                // Load cities
                document.getElementById('city_search').disabled = true;
                document.getElementById('city_search').placeholder = 'Loading...';
                
                fetch(`/cities/${stateId}`)
                    .then(res => res.json())
                    .then(data => {
                        citiesData = data;
                        const citySearch = document.getElementById('city_search');
                        const cityDropdown = document.getElementById('city_dropdown');
                        const cityHidden = document.getElementById('city_id');
                        
                        citySearch.disabled = false;
                        citySearch.placeholder = 'Search City...';
                        
                        initSearchableDropdown(citySearch, cityDropdown, cityHidden, citiesData, function(cityId) {
                            // Reset market
                            document.getElementById('market_search').value = '';
                            document.getElementById('market_id').value = '';
                            
                            // Load markets
                            document.getElementById('market_search').disabled = true;
                            document.getElementById('market_search').placeholder = 'Loading...';
                            
                            fetch(`/markets/${cityId}`)
                                .then(res => res.json())
                                .then(data => {
                                    marketsData = data;
                                    const marketSearch = document.getElementById('market_search');
                                    const marketDropdown = document.getElementById('market_dropdown');
                                    const marketHidden = document.getElementById('market_id');
                                    
                                    marketSearch.disabled = false;
                                    marketSearch.placeholder = 'Search Market...';
                                    
                                    initSearchableDropdown(marketSearch, marketDropdown, marketHidden, marketsData);
                                });
                        });
                    });
            });
        });
});
</script>




<!-- LOAD ALL REQUIREMENTS -->
<script>
document.getElementById('allRequirementsModal')
    .addEventListener('shown.bs.modal', function () {
        loadRequirements();
});
</script>

<script>
function loadRequirements(page = 1)
{
    document.getElementById('requirementTable').innerHTML =
        `<tr><td colspan="9" class="text-center">Loading...</td></tr>`;

    document.getElementById('requirementPagination').innerHTML = '';

    fetch(`/requirements/list?page=${page}`, {
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(res => res.json())
    .then(res => {

        if(!res.data || res.data.length === 0){
            document.getElementById('requirementTable').innerHTML = `
                <tr>
                    <td colspan="9" class="text-center">
                        No records found
                    </td>
                </tr>`;
            return;
        }

        let rows = '';

        let start = res.total - ((res.current_page - 1) * res.per_page);

        res.data.forEach((r, index) => {
            rows += `
            <tr>
                <td>${start - index}</td>
                <td>${r.brand?.name ?? '-'}</td>
                <td>${r.poc?.name ?? '-'}</td>
                <td>${r.state?.name ?? '-'}</td>
                <td>${r.city?.name ?? '-'}</td>
                <td>${r.market?.name ?? '-'}</td>
                <td>${r.budget}</td>
                <td>${r.type}</td>
                <td class="text-nowrap">
                    <button class="btn btn-info btn-sm me-1"
                        onclick="viewRequirement(${r.id})">
                        View
                    </button>

                    <button class="btn btn-warning btn-sm me-1"
                        onclick="editRequirement(${r.id})">
                        Edit
                    </button>

                    <button class="btn btn-danger btn-sm"
                        onclick="deleteRequirement(${r.id})">
                        Delete
                    </button>
                </td>
            </tr>`;
        });

        document.getElementById('requirementTable').innerHTML = rows;

        if (res.total <= res.per_page) {
    document.getElementById('requirementPagination').innerHTML = '';
    return;
}
        let pagination = '<div class="btn-group">';

        pagination += `
        <button class="btn btn-sm btn-outline-primary"
            ${res.current_page === 1 ? 'disabled' : ''}
            onclick="loadRequirements(${res.current_page - 1})">
            &laquo; Prev
        </button>
        `;

        let startPage = Math.max(1, res.current_page - 2);
        let endPage   = Math.min(res.last_page, res.current_page + 2);

        for(let i = startPage; i <= endPage; i++){
            pagination += `
            <button class="btn btn-sm ${res.current_page === i ? 'btn-primary' : 'btn-outline-primary'}"
                onclick="loadRequirements(${i})">
                ${i}
            </button>
            `;
        }

        pagination += `
        <button class="btn btn-sm btn-outline-primary"
            ${res.current_page === res.last_page ? 'disabled' : ''}
            onclick="loadRequirements(${res.current_page + 1})">
            Next &raquo;
        </button>
        `;

        pagination += '</div>';

        document.getElementById('requirementPagination').innerHTML = pagination;

    })
    .catch(err => {
        console.error(err);
        alert('Failed to load requirements');
    });
}
</script>

<!-- VIEW REQUIREMENT -->
<script>
function viewRequirement(id){
    fetch(`/requirements/${id}`, {
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        }
    })
    .then(res => res.json())
    .then(r => {
        document.getElementById('viewContent').innerHTML = `
           <table class="table table-bordered text-center align-middle">

    <tr class="table-light fw-bold">
        <td>Brand</td>
        <td>POC</td>
        <td>State</td>
        <td>City</td>
        <td>Market</td>
    </tr>
    <tr>
        <td>${r.brand?.name ?? '-'}</td>
        <td>${r.poc?.name ?? '-'}</td>
        <td>${r.state?.name ?? '-'}</td>
        <td>${r.city?.name ?? '-'}</td>
        <td>${r.market?.name ?? '-'}</td>
    </tr>

    <tr class="table-light fw-bold">
        <td>Budget</td>
        <td>Type</td>
        <td>Size</td>
        <td>Floor</td>
        <td>Timeline</td>
    </tr>
    <tr>
        <td>${r.budget}</td>
        <td>${r.type}</td>
        <td>${r.size_range}</td>
        <td>${r.floor_preference}</td>
        <td>${r.timeline}</td>
    </tr>

    <tr class="table-light fw-bold">
        <td colspan="5">Frontage</td>
    </tr>
    <tr>
        <td colspan="5">${r.footage}</td>
    </tr>

</table>

        `;

        new bootstrap.Modal(
            document.getElementById('viewModal')
        ).show();
    });
}
</script>

<!-- EDIT REQUIREMENT -->
<script>
function editRequirement(id){

    fetch(`/requirements/${id}`, {
        headers:{
            'Accept':'application/json',
            'X-Requested-With':'XMLHttpRequest'
        }
    })
    .then(res => res.json())
    .then(r => {

        document.getElementById('editContent').innerHTML = `
<form id="editForm">
<div class="row g-3">

    <div class="col-md-3">
        <label>Brand <span class="required">*</span></label>
        <select class="form-select" name="brand_id" id="edit_brand_id">
            <?php $__currentLoopData = $brands; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $brand): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <option value="<?php echo e($brand->id); ?>"><?php echo e($brand->name); ?></option>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </select>
    </div>

    <div class="col-md-3">
        <label>Brand POC <span class="required">*</span></label>
        <select class="form-select" name="brand_poc_id" id="edit_brand_poc_id">
            <option value="">Select Brand First</option>
        </select>
    </div>

    <div class="col-md-3">
        <label>State <span class="required">*</span></label>
        <select class="form-select" name="state_id" id="edit_state_id"></select>
    </div>

    <div class="col-md-3">
        <label>City <span class="required">*</span></label>
        <select class="form-select" name="city_id" id="edit_city_id"></select>
    </div>

    <div class="col-md-3">
        <label>Market <span class="required">*</span></label>
        <select class="form-select" name="market_id" id="edit_market_id"></select>
    </div>

    <div class="col-md-3">
        <label>Budget <span class="required">*</span></label>
        <input class="form-control" name="budget" value="${r.budget}">
    </div>

    <div class="col-md-3">
        <label>Type <span class="required">*</span></label>
        <select class="form-select" name="type">
            <option ${r.type=='Retail'?'selected':''}>Retail</option>
            <option ${r.type=='Showroom'?'selected':''}>Showroom</option>
            <option ${r.type=='Warehouse'?'selected':''}>Warehouse</option>
            <option ${r.type=='Office'?'selected':''}>Office</option>
        </select>
    </div>

    <div class="col-md-3">
        <label>Size <span class="required">*</span></label>
        <input class="form-control" name="size_range" value="${r.size_range}">
    </div>

   <div class="col-md-3">
    <label>Floor <span class="required">*</span></label>
    <select class="form-control" name="floor_preference">
        <option value="">Select Floor</option>
      <option value="LGF" ${r.floor_preference == 'LGF' ? 'selected' : ''}>LGF</option>
<option value="GF" ${r.floor_preference == 'GF' ? 'selected' : ''}>GF</option>
<option value="FF" ${r.floor_preference == 'FF' ? 'selected' : ''}>FF</option>
<option value="SF" ${r.floor_preference == 'SF' ? 'selected' : ''}>SF</option>
<option value="3rd floor" ${r.floor_preference == '3rd floor' ? 'selected' : ''}>3rd floor</option>
<option value="4th floor" ${r.floor_preference == '4th floor' ? 'selected' : ''}>4th floor</option>

    </select>
</div>


   <div class="col-md-3">
    <label>Timeline/months <span class="required">*</span></label>
    <select class="form-control" name="timeline">
        <option value="">Select Timeline</option>
       
        <option value="1 Month" ${r.timeline == '1 Month' ? 'selected' : ''}>1 Month</option>
        <option value="2 Months" ${r.timeline == '2 Months' ? 'selected' : ''}>2 Months</option>
        <option value="3 Months" ${r.timeline == '3 Months' ? 'selected' : ''}>3 Months</option>
        <option value="4 Months" ${r.timeline == '4 Months' ? 'selected' : ''}>4 Months</option>
        <option value="5 Months" ${r.timeline == '5 Months' ? 'selected' : ''}>5 Months</option>
        <option value="6 Months" ${r.timeline == '6 Months' ? 'selected' : ''}>6 Months</option>
        <option value="7 Months" ${r.timeline == '7 Months' ? 'selected' : ''}>7 Months</option>
        <option value="8 Months" ${r.timeline == '8 Months' ? 'selected' : ''}>8 Months</option>
        <option value="9 Months" ${r.timeline == '9 Months' ? 'selected' : ''}>9 Months</option>
        <option value="10 Months" ${r.timeline == '10 Months' ? 'selected' : ''}>10 Months</option>
        <option value="11 Months" ${r.timeline == '11 Months' ? 'selected' : ''}>11 Months</option>
        <option value="12 Months" ${r.timeline == '12 Months' ? 'selected' : ''}>12 Months</option>
    </select>
</div>


    <div class="col-md-3">
        <label>Frontage <span class="required">*</span></label>
        <input class="form-control" name="footage" value="${r.footage}">
    </div>
</div>

<button class="btn btn-primary w-100 mt-3">Update</button>
</form>
`;

        const brandSel  = document.getElementById('edit_brand_id');
        const pocSel    = document.getElementById('edit_brand_poc_id');
        const stateSel  = document.getElementById('edit_state_id');
        const citySel   = document.getElementById('edit_city_id');
        const marketSel = document.getElementById('edit_market_id');

        // ================= STATE → CITY → MARKET (FIXED) =================

// Load States
fetch('/states')
.then(res => res.json())
.then(states => {
    let html = '<option value="">Select State</option>';
    states.forEach(s => {
        html += `<option value="${s.id}">${s.name}</option>`;
    });
    stateSel.innerHTML = html;
    stateSel.value = r.state_id;

    loadCities(r.state_id);
});

function loadCities(stateId){
    citySel.innerHTML = '<option value="">Loading...</option>';
    marketSel.innerHTML = '<option value="">Select City First</option>';

    fetch(`/cities/${stateId}`)
    .then(res => res.json())
    .then(cities => {
        let html = '<option value="">Select City</option>';
        cities.forEach(c => {
            html += `<option value="${c.id}">${c.name}</option>`;
        });
        citySel.innerHTML = html;
        citySel.value = r.city_id;

        loadMarkets(r.city_id);
    });
}

function loadMarkets(cityId){
    marketSel.innerHTML = '<option value="">Loading...</option>';

    fetch(`/markets/${cityId}`)
    .then(res => res.json())
    .then(markets => {
        let html = '<option value="">Select Market</option>';
        markets.forEach(m => {
            html += `<option value="${m.id}">${m.name}</option>`;
        });
        marketSel.innerHTML = html;
        marketSel.value = r.market_id;
    });
}

// Change events
stateSel.onchange = () => loadCities(stateSel.value);
citySel.onchange  = () => loadMarkets(citySel.value);


        // Set initial brand value
        brandSel.value = r.brand_id;

        // Function to load POC for a brand
        function loadPocOptions(brandId, targetSelect) {
            if (!brandId) {
                targetSelect.innerHTML = '<option value="">Select Brand First</option>';
                $('#edit_brand_poc_id').trigger('change.select2');
                return;
            }

            targetSelect.innerHTML = '<option value="">Loading...</option>';
            $('#edit_brand_poc_id').trigger('change.select2');

            fetch(`/brands/${brandId}/pocs`)
                .then(res => res.json())
                .then(pocs => {
                    let html = '<option value="">Select Brand POC</option>';
                    if (pocs.length === 0) {
                        html = '<option value="">No POC Found</option>';
                    } else {
                        pocs.forEach(p => {
                            html += `<option value="${p.id}">${p.name}</option>`;
                        });
                    }
                    targetSelect.innerHTML = html;
                    targetSelect.value = (brandId === r.brand_id) ? r.brand_poc_id : '';
                    $('#edit_brand_poc_id').trigger('change.select2'); // Refresh Select2
                })
                .catch(() => {
                    targetSelect.innerHTML = '<option value="">Error loading POC</option>';
                    $('#edit_brand_poc_id').trigger('change.select2');
                });
        }

        // Initial POC load
        loadPocOptions(r.brand_id, pocSel);

        // On brand change, reload POC
        brandSel.addEventListener('change', function(){
            loadPocOptions(this.value, pocSel);
        });

       


        stateSel.addEventListener('change', () => loadCities(stateSel.value));
        citySel.addEventListener('change', () => loadMarkets(citySel.value));

        // Show modal
        new bootstrap.Modal(document.getElementById('editModal')).show();

        // Initialize Select2 AFTER modal is shown
        setTimeout(() => {
            $('#edit_brand_id').select2({
                dropdownParent: $('#editModal .modal-content'),
                placeholder: 'Select Brand',
                width: '100%',
                minimumResultsForSearch: 0
            });

            $('#edit_brand_poc_id').select2({
                dropdownParent: $('#editModal .modal-content'),
                placeholder: 'Select Brand POC',
                width: '100%',
                minimumResultsForSearch: 0
            });

            $('#edit_state_id').select2({
                dropdownParent: $('#editModal .modal-content'),
                placeholder: 'Search State...',
                width: '100%',
                minimumResultsForSearch: 0
            });

            $('#edit_city_id').select2({
                dropdownParent: $('#editModal .modal-content'),
                placeholder: 'Search City...',
                width: '100%',
                minimumResultsForSearch: 0
            });

            $('#edit_market_id').select2({
                dropdownParent: $('#editModal .modal-content'),
                placeholder: 'Search Market...',
                width: '100%',
                minimumResultsForSearch: 0
            });

            // Final refresh after all init
            $('#edit_brand_poc_id').trigger('change.select2');
        }, 500);

        document.getElementById('editForm').onsubmit = function(e){
            e.preventDefault();
            updateRequirement(id, new FormData(this));
        };
    });
}
</script>
<!-- UPDATE REQUIREMENT -->
<script>
function updateRequirement(id, formData){

    fetch(`/requirements/${id}/update`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN':
                document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: formData
    })
    .then(async res => {

        if (res.status === 422) {
            const data = await res.json();

            let messages = '';
            Object.values(data.errors).forEach(err => {
                messages += err[0] + '\n';
            });

            alert(messages);
            throw new Error('Validation failed');
        }

        return res.json();
    })
    .then(data => {
        if(data.success){
            loadRequirements();
            bootstrap.Modal
                .getInstance(document.getElementById('editModal'))
                .hide();
            alert(data.message);
        }
    })
    .catch(err => {
        console.error(err);
    });
}
</script>

<!-- DELETE REQUIREMENT -->
<script>
function deleteRequirement(id){
    if(!confirm('Are you sure you want to delete this requirement?')){
        return;
    }

    fetch(`/requirements/${id}`, {
        method: 'DELETE',
        headers: {
            'X-CSRF-TOKEN':
                document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        }
    })
    .then(res => {
        if(!res.ok){
            throw new Error('Delete request failed');
        }
        return res.json();
    })
    .then(data => {
        if(data.success){
            loadRequirements();
        } else {
            alert('Delete failed');
        }
    })
    .catch(err => {
        console.error(err);
        alert('Delete error');
    });
}
</script>
<!-- BRAND + POC initialization -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<script>
$(document).ready(function() {

    $('#brand_id').select2({
        placeholder: "Select Brand",
    
        width: '100%'
    });

    $('#brand_poc_id').select2({
        placeholder: "Select Brand POC",
        
        width: '100%'
    });

    $('#brand_id').on('change', function() {
        const brandId = $(this).val();
        const pocSelect = $('#brand_poc_id');

        pocSelect.html('<option value="">Loading...</option>').trigger('change');

        if (!brandId) {
            pocSelect.html('<option value="">Select Brand First</option>').trigger('change');
            return;
        }

        $.ajax({
            url: `/brands/${brandId}/pocs`,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                console.log("POCs from server:", data);  // ← debugging के लिए देखना

                let html = '<option value="">Select Brand POC</option>';

                if (!data || data.length === 0) {
                    html = '<option value="">No POC Found</option>';
                } else {
                    data.forEach(poc => {
                        html += `<option value="${poc.id}">${poc.name}</option>`;
                    });
                }

                pocSelect.html(html).trigger('change');
            },
            error: function(xhr, status, error) {
                console.error("Error loading POC:", status, error, xhr.responseText);
                pocSelect.html('<option value="">Error loading POC</option>').trigger('change');
            }
        });
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {

    const form = document.querySelector('form[action="/requirements"]');
    const submitBtn = form?.querySelector('.btn-req');

    if (!form || !submitBtn) return;

    let submitted = false; // 🔒 LOCK

    form.addEventListener('submit', function (e) {

        if (submitted) {
            e.preventDefault();   // ❌ second submit blocked
            return false;
        }

        submitted = true; // ✅ first submit allowed

        submitBtn.disabled = true;
        submitBtn.innerHTML = `
            <span class="spinner-border spinner-border-sm me-2"></span>
            Saving Requirement...
        `;
    });

});
</script>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/ixapl/public_html/retailcrm.ixapl.com/resources/views/requirement/create.blade.php ENDPATH**/ ?>