/* lockers.js — লকার ম্যানেজমেন্ট (party_search integrated) */
var psInstance = null;

function doAlert(msg, type) {
    var el = document.getElementById('alertBox');
    if (!el) return;
    el.textContent = msg;
    el.style.display = 'block';
    el.style.background = type === 'ok' ? '#1a4a2e' : '#4a1a1a';
    el.style.color = type === 'ok' ? '#2ecc71' : '#e74c3c';
    el.style.border = '1px solid ' + (type==='ok'?'#2ecc71':'#e74c3c');
    setTimeout(function(){ el.style.display='none'; }, 3500);
}

function loadLockers() {
    var q      = (document.getElementById('searchInput')||{}).value||'';
    var status = (document.getElementById('statusFilter')||{}).value||'';
    fetch('../api/lockers/get_lockers.php?q='+encodeURIComponent(q)+'&status='+status, {credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
        var list = document.getElementById('lockerList');
        if (!list) return;
        if (!res.success || !res.data || !res.data.length) {
            list.innerHTML = '<div style="text-align:center;padding:40px;color:#aaa;font-size:16px">কোনো লকার পাওয়া যায়নি</div>';
            return;
        }
        list.innerHTML = res.data.map(function(l){
            var badge = l.status==='active'
                ? '<span style="background:#1a4a2e;color:#2ecc71;padding:3px 10px;border-radius:12px;font-size:13px">✅ চালু</span>'
                : '<span style="background:#4a1a1a;color:#e74c3c;padding:3px 10px;border-radius:12px;font-size:13px">❌ বন্ধ</span>';
            return '<div style="background:#0f1a30;border-radius:12px;padding:16px;margin-bottom:14px;border:1px solid #1e3a5f">' +
                '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">' +
                  '<span style="color:#f5b800;font-weight:bold;font-size:18px">'+l.name+'</span>' +
                  badge +
                '</div>' +
                (l.phone ? '<div style="color:#aaa;font-size:14px;margin-bottom:4px">📞 '+l.phone+'</div>' : '') +
                (l.address ? '<div style="color:#aaa;font-size:14px;margin-bottom:10px">📍 '+l.address+'</div>' : '') +
                '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px">' +
                  '<div style="background:#0a1628;border-radius:8px;padding:12px;text-align:center">' +
                    '<div style="color:#aaa;font-size:13px;margin-bottom:4px">মাসিক ভাড়া</div>' +
                    '<div style="color:#f5b800;font-weight:bold;font-size:18px">'+parseFloat(l.monthly_rent_rate).toFixed(2)+'%</div>' +
                  '</div>' +
                  '<div style="background:#0a1628;border-radius:8px;padding:12px;text-align:center">' +
                    '<div style="color:#aaa;font-size:13px;margin-bottom:4px">বন্ধক সংখ্যা</div>' +
                    '<div style="color:#fff;font-weight:bold;font-size:18px">'+(l.pledge_count||0)+'টি</div>' +
                  '</div>' +
                '</div>' +
                (l.notes ? '<div style="background:#0a1628;border-radius:6px;padding:8px 12px;color:#aaa;font-size:14px;margin-bottom:12px">📝 '+l.notes+'</div>' : '') +
                '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">' +
                  '<button onclick="openEdit('+JSON.stringify(l).replace(/"/g,'&quot;')+')" style="padding:12px;border-radius:8px;background:#1e3a6e;color:#fff;border:none;font-size:15px;cursor:pointer">✏️ সম্পাদনা</button>' +
                  '<button onclick="doDelete('+l.id+')" style="padding:12px;border-radius:8px;background:#6e1e1e;color:#fff;border:none;font-size:15px;cursor:pointer">🗑️ মুছুন</button>' +
                '</div>' +
            '</div>';
        }).join('');
    }).catch(function(){ doAlert('লোড করতে সমস্যা','err'); });
}

/* ===== Modal ===== */
var editId = null;

function openAdd() {
    editId = null;
    document.getElementById('modalTitle').textContent = 'নতুন লকার';
    document.getElementById('fRate').value   = '4';
    document.getElementById('fBal').value    = '0';
    document.getElementById('fStatus').value = 'active';
    document.getElementById('fNotes').value  = '';
    if (psInstance) psInstance.clear();
    document.getElementById('fName').value   = '';
    document.getElementById('fPhone').value  = '';
    document.getElementById('fAddr').value   = '';
    document.getElementById('lockerModal').style.display = 'flex';
}

function openEdit(l) {
    editId = l.id;
    document.getElementById('modalTitle').textContent = 'লকার সম্পাদনা';
    document.getElementById('fName').value   = l.name  || '';
    document.getElementById('fPhone').value  = l.phone || '';
    document.getElementById('fAddr').value   = l.address || '';
    document.getElementById('fRate').value   = l.monthly_rent_rate || '4';
    document.getElementById('fBal').value    = l.opening_balance || '0';
    document.getElementById('fStatus').value = l.status || 'active';
    document.getElementById('fNotes').value  = l.notes || '';
    if (psInstance) psInstance.clear();
    /* pre-fill party if exists */
    if (l.party_id && l.party_name) {
        psInstance && psInstance.setParty({id:l.party_id, name:l.party_name, phone:l.phone||''});
    }
    document.getElementById('lockerModal').style.display = 'flex';
}

function closeModal() {
    document.getElementById('lockerModal').style.display = 'none';
}

function doSave() {
    var name  = document.getElementById('fName').value.trim();
    var phone = document.getElementById('fPhone').value.trim();
    var rate  = document.getElementById('fRate').value.trim();
    if (!name) { doAlert('নাম দিন','err'); return; }
    if (!rate)  { doAlert('ভাড়ার হার দিন','err'); return; }

    var party = psInstance ? psInstance.getParty() : null;
    var data = {
        party_id: party ? party.id : null,
        name: name,
        phone: phone,
        address: document.getElementById('fAddr').value.trim(),
        monthly_rent_rate: rate,
        opening_balance: document.getElementById('fBal').value||'0',
        status: document.getElementById('fStatus').value,
        notes: document.getElementById('fNotes').value.trim()
    };
    if (editId) data.id = editId;

    var url = editId ? '../api/lockers/update_locker.php' : '../api/lockers/add_locker.php';
    document.getElementById('btnSave').disabled = true;
    document.getElementById('btnSave').textContent = 'সেভ হচ্ছে...';

    fetch(url, {method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/json'}, body:JSON.stringify(data)})
    .then(function(r){return r.json();})
    .then(function(res){
        if (res.success) {
            closeModal();
            doAlert(editId?'আপডেট হয়েছে ✅':'লকার যোগ হয়েছে ✅','ok');
            loadLockers();
        } else {
            doAlert(res.message||'সমস্যা হয়েছে','err');
        }
        document.getElementById('btnSave').disabled = false;
        document.getElementById('btnSave').textContent = '✅ সেভ করুন';
    }).catch(function(){
        doAlert('নেটওয়ার্ক সমস্যা','err');
        document.getElementById('btnSave').disabled = false;
        document.getElementById('btnSave').textContent = '✅ সেভ করুন';
    });
}

function doDelete(id) {
    if (!confirm('এই লকার মুছে ফেলবেন?')) return;
    fetch('../api/lockers/delete_locker.php', {method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/json'}, body:JSON.stringify({id:id})})
    .then(function(r){return r.json();})
    .then(function(res){
        if (res.success) { doAlert('মুছে ফেলা হয়েছে','ok'); loadLockers(); }
        else doAlert(res.message||'সমস্যা','err');
    });
}

document.addEventListener('DOMContentLoaded', function(){
    loadLockers();

    /* party search init — inside modal */
    if (typeof initPartySearch === 'function') {
        psInstance = initPartySearch('partySearchContainer', {
            role: 'locker',
            apiBase: '../api',
            placeholder: 'লকার হোল্ডার খুঁজুন',
            onSelect: function(p) {
                if (p) {
                    document.getElementById('fName').value  = p.name;
                    document.getElementById('fPhone').value = p.phone || '';
                    document.getElementById('fAddr').value  = p.address || '';
                }
            }
        });
    }

    var searchInput  = document.getElementById('searchInput');
    var statusFilter = document.getElementById('statusFilter');
    var addBtn       = document.getElementById('addBtn');
    var btnSave      = document.getElementById('btnSave');
    var btnCancel    = document.getElementById('btnCancel');

    if (searchInput)  searchInput.addEventListener('input', loadLockers);
    if (statusFilter) statusFilter.addEventListener('change', loadLockers);
    if (addBtn)       addBtn.addEventListener('click', openAdd);
    if (btnSave)      btnSave.addEventListener('click', doSave);
    if (btnCancel)    btnCancel.addEventListener('click', closeModal);
});