<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('All Bookings')}"></head>
<body>
<nav th:replace="~{fragments/layout :: adminbar}"></nav>

<section>
    <div class="container">
        <div class="page-header">
            <h1>All Bookings</h1>
            <button class="btn btn-primary btn-sm" type="button" onclick="openBookingModal()">+ Add Booking</button>
        </div>

        <div class="cars-toolbar">
            <input class="cars-search" id="bkSearch" type="text"
                   placeholder="Search customer or car…" oninput="renderRows()"/>
            <span style="display:flex;gap:10px;align-items:center">
                <select id="bkFilter" class="cars-search" style="min-width:160px" onchange="renderRows()">
                    <option value="">All statuses</option>
                    <option th:each="s : ${T(com.mvrent.carrental.model.BookingStatus).values()}"
                            th:value="${s}" th:text="${s}"></option>
                </select>
                <span id="bkCount" style="color:#888;font-size:13px"></span>
            </span>
        </div>

        <div class="table-wrap">
            <table>
                <thead>
                <tr>
                    <th data-sort="id">ID</th><th data-sort="customerName">Customer</th><th data-sort="carName">Car</th>
                    <th data-sort="driverName">Driver</th><th data-sort="pickupDate">Dates</th>
                    <th data-sort="revenueOwner">Owner</th><th data-sort="totalAmount">Total</th>
                    <th data-sort="balance">Paid</th>
                    <th data-sort="status">Status</th><th></th>
                </tr>
                </thead>
                <tbody id="bkRows">
                <tr><td colspan="10" class="table-loading">Loading bookings…</td></tr>
                </tbody>
            </table>
        </div>
        <div class="pager" id="bkPager"></div>
    </div>
</section>

<!-- ============ Add Booking modal ============ -->
<div class="modal-overlay" id="bModal">
    <div class="modal-card" style="max-width:720px">
        <div class="modal-head">
            <h2>New Booking <span class="tag">Counter</span></h2>
            <button class="modal-close" type="button" onclick="closeBookingModal()">&times;</button>
        </div>
        <div class="modal-body">
            <form id="bForm" onsubmit="return false">

                <!-- Customer -->
                <div class="form-section-label">Customer</div>
                <div class="seg" style="margin-bottom:12px">
                    <button type="button" class="seg-btn active" id="seg-existing" onclick="custMode('existing')">Existing</button>
                    <button type="button" class="seg-btn" id="seg-walkin" onclick="custMode('walkin')">Walk-in</button>
                </div>

                <div id="custExisting">
                    <div class="form-group field">
                        <label>Select customer</label>
                        <select id="b_customerId">
                            <option value="">— choose a customer —</option>
                            <option th:each="c : ${customers}" th:value="${c.id}"
                                    th:text="${c.fullName + (c.phone != null ? ' · ' + c.phone : '')}">Name</option>
                        </select>
                    </div>
                </div>

                <div id="custWalkin" style="display:none">
                    <div class="form-grid2">
                        <div class="form-group field"><label>Full name</label><input type="text" id="b_customerName" placeholder="e.g. Anitha Menon"/></div>
                        <div class="form-group field"><label>Phone</label><input type="tel" id="b_customerPhone" placeholder="Optional"/></div>
                        <div class="form-group field" style="grid-column:1 / -1"><label>Email</label><input type="email" id="b_customerEmail" placeholder="Optional"/></div>
                    </div>
                </div>

                <!-- Vehicle & dates -->
                <div class="form-section-label" style="margin-top:6px">Vehicle &amp; Trip</div>
                <div class="form-grid2">
                    <div class="form-group field" style="grid-column:1 / -1">
                        <label>Car</label>
                        <select id="b_carId" onchange="estimate()">
                            <option value="">— choose a car —</option>
                            <option th:each="c : ${availableCars}" th:value="${c.id}"
                                    th:attr="data-price=${c.pricePerDay}"
                                    th:text="${c.make + ' ' + c.model + ' (' + c.registrationNumber + ') · ' + currencySymbol + c.pricePerDay + '/day'}">Car</option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>Rental unit</label>
                        <select id="b_rentalUnit" onchange="estimate()">
                            <option value="DAY">Per day</option>
                            <option value="MONTH">Per month</option>
                        </select>
                    </div>
                    <div class="form-group field">
                        <label>&nbsp;</label>
                        <label style="font-weight:500;color:#444;display:flex;align-items:center;gap:8px;height:42px">
                            <input type="checkbox" id="b_withDriver" onchange="toggleDriver()"/> With driver
                        </label>
                    </div>
                    <div class="form-group field"><label>Pickup date</label><input type="date" id="b_pickupDate" onchange="estimate()"/></div>
                    <div class="form-group field"><label>Return date</label><input type="date" id="b_returnDate" onchange="estimate()"/></div>
                    <div class="form-group field" id="driverWrap" style="grid-column:1 / -1;display:none">
                        <label>Driver</label>
                        <select id="b_driverId" onchange="estimate()">
                            <option value="">— choose a driver —</option>
                            <option th:each="d : ${availableDrivers}" th:value="${d.id}"
                                    th:attr="data-daily=${d.dailyCharge}"
                                    th:text="${d.name + (d.dailyCharge != null ? ' · ' + currencySymbol + d.dailyCharge + '/day' : '')}">Driver</option>
                        </select>
                    </div>
                    <div class="form-group field"><label>Pickup location</label><input type="text" id="b_pickupLocation" placeholder="e.g. Kochi Airport"/></div>
                    <div class="form-group field"><label>Drop location</label><input type="text" id="b_dropLocation" placeholder="e.g. Trivandrum"/></div>
                </div>

                <div class="booking-estimate" id="bEstimate" style="display:none">
                    <span>Estimated charge <small>(before tax)</small></span>
                    <strong id="bEstimateVal">—</strong>
                </div>
            </form>
        </div>
        <div class="modal-foot">
            <button class="btn btn-ghost btn-sm" type="button" onclick="closeBookingModal()">Cancel</button>
            <button class="btn btn-primary btn-sm" id="bSaveBtn" type="button" onclick="saveBooking()">Create Booking</button>
        </div>
    </div>
</div>

<!-- ============ Payments modal ============ -->
<div class="modal-overlay" id="payModal">
    <div class="modal-card" style="max-width:620px">
        <div class="modal-head">
            <h2>Payments <span class="tag" id="payBkTag">#0</span></h2>
            <button class="modal-close" type="button" onclick="closePayments()">&times;</button>
        </div>
        <div class="modal-body">
            <div class="pay-summary">
                <div><span>Total</span><strong id="paySumTotal">—</strong></div>
                <div><span>Paid</span><strong id="paySumPaid" style="color:#1f9d55">—</strong></div>
                <div><span>Balance</span><strong id="paySumBal" style="color:#c0392b">—</strong></div>
            </div>

            <div class="media-add" style="margin:16px 0">
                <h5>Record a payment</h5>
                <div class="form-grid2">
                    <div class="form-group field"><label>Amount</label><input type="number" step="0.01" min="0" id="pay_amount"/></div>
                    <div class="form-group field">
                        <label>Method</label>
                        <select id="pay_method">
                            <option th:each="m : ${T(com.mvrent.carrental.model.PaymentMethod).values()}"
                                    th:value="${m}" th:text="${#strings.replace(m, '_', ' ')}"></option>
                        </select>
                    </div>
                    <div class="form-group field"><label>Reference</label><input type="text" id="pay_reference" placeholder="UPI / txn / cheque no."/></div>
                    <div class="form-group field"><label>Date</label><input type="date" id="pay_paidAt"/></div>
                    <div class="form-group field" style="grid-column:1 / -1"><label>Notes</label><input type="text" id="pay_notes"/></div>
                </div>
                <button class="btn btn-primary btn-sm" id="payAddBtn" type="button" onclick="recordPayment()" style="margin-top:6px">Add Payment</button>
            </div>

            <table class="pay-table">
                <thead><tr><th>Date</th><th>Method</th><th>Reference</th><th>Amount</th><th></th></tr></thead>
                <tbody id="payRows"><tr><td colspan="5" class="media-empty" style="background:none;border:none">No payments yet.</td></tr></tbody>
            </table>
        </div>
        <div class="modal-foot">
            <button class="btn btn-ghost btn-sm" type="button" onclick="closePayments()">Close</button>
        </div>
    </div>
</div>

<div class="toast-wrap" id="toasts"></div>

<script th:inline="javascript">
/*<![CDATA[*/
const CSRF_TOKEN  = /*[[${_csrf.token}]]*/ '';
const CSRF_HEADER = /*[[${_csrf.headerName}]]*/ 'X-CSRF-TOKEN';
const CUR         = /*[[${currencySymbol}]]*/ '₹';
const STATUSES = ['PENDING','CONFIRMED','CANCELLED','COMPLETED'];
/*]]>*/
</script>

<script src="/js/admin-table.js"></script>
<script>
const API='/admin/api/bookings';
let BOOKINGS=[];
const ST = { sortKey: null, sortDir: 1, page: 1, pageSize: 10 };
function esc(s){ return (s==null?'':String(s)).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }

function loadBookings(){ fetch(API).then(r=>r.json()).then(d=>{BOOKINGS=d;renderRows();})
  .catch(()=>{document.getElementById('bkRows').innerHTML='<tr><td colspan="9" class="table-loading">Failed to load.</td></tr>';}); }

function statusSelect(id, cur){
  return '<select class="status-select status-'+cur.toLowerCase()+'" onchange="updateStatus('+id+', this)">'+
    STATUSES.map(s=>'<option value="'+s+'"'+(s===cur?' selected':'')+'>'+s+'</option>').join('')+'</select>';
}
function payCell(b){
  const total=Number(b.totalAmount||0), paid=Number(b.amountPaid||0), bal=Number(b.balance||0);
  if(total<=0) return '<small style="color:#888">—</small>';
  if(bal<=0.0001) return '<span class="dash-pill pill-confirmed">PAID</span>';
  if(paid>0) return '<span class="dash-pill pill-pending">'+CUR+paid+'</span><br><small style="color:#c0392b">'+CUR+bal.toFixed(0)+' due</small>';
  return '<span class="dash-pill pill-cancelled">Unpaid</span>';
}

function renderRows(){
  const q=(document.getElementById('bkSearch').value||'').toLowerCase();
  const f=document.getElementById('bkFilter').value;
  let rows=BOOKINGS.filter(b=>(!q||((b.customerName||'')+' '+(b.carName||'')).toLowerCase().includes(q))
                                 && (!f||b.status===f));
  rows = AdminTable.sort(rows, ST.sortKey, ST.sortDir);
  document.getElementById('bkCount').textContent=rows.length+' booking'+(rows.length===1?'':'s');
  const tb=document.getElementById('bkRows');
  if(!rows.length){ tb.innerHTML='<tr><td colspan="10" class="table-loading">No bookings found.</td></tr>';
    document.getElementById('bkPager').innerHTML=''; return; }
  const pg = AdminTable.paginate(rows, ST.page, ST.pageSize);
  tb.innerHTML=pg.slice.map(b=>`
    <tr id="bk-${b.id}">
      <td>#${b.id}</td>
      <td><div>${esc(b.customerName)}</div><small style="color:#888">${esc(b.customerEmail)}</small></td>
      <td>${esc(b.carName)}</td>
      <td>${b.withDriver&&b.driverName?esc(b.driverName):'Self-drive'}</td>
      <td><div>${b.pickupDate}</div><small style="color:#888">${b.returnDate}</small></td>
      <td>${esc(b.revenueOwner)}${b.vendorName?'<br><small style="color:#888">'+esc(b.vendorName)+'</small>':''}</td>
      <td>${CUR}${b.totalAmount}</td>
      <td>${payCell(b)}</td>
      <td>${statusSelect(b.id, b.status)}</td>
      <td><div class="row-actions">
        <button class="icon-btn" title="Payments" onclick="openPayments(${b.id})">&#128181;</button>
        <a class="icon-btn" title="Invoice" href="/admin/bookings/${b.id}/invoice">&#129534;</a>
      </div></td>
    </tr>`).join('');
  ST.page = pg.page;
  AdminTable.pager(document.getElementById('bkPager'), pg.page, pg.total, p => { ST.page = p; renderRows(); });
}

function updateStatus(id, sel){
  const status=sel.value;
  sel.className='status-select status-'+status.toLowerCase();
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+id+'/status?status='+status, {method:'POST', headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{
      if(res.ok&&res.body.ok){
        const b=BOOKINGS.find(x=>x.id===id); if(b) b.status=status;
        toast('Booking #'+id+' set to '+status,'ok');
      } else { toast('Could not update','err'); loadBookings(); }
    }).catch(()=>{ toast('Network error','err'); loadBookings(); });
}

function toast(msg,kind){ const t=document.createElement('div'); t.className='toast '+(kind||'ok'); t.textContent=msg;
  document.getElementById('toasts').appendChild(t);
  setTimeout(()=>{t.style.opacity='0';t.style.transition='opacity .3s';setTimeout(()=>t.remove(),300);},2600); }

AdminTable.attachSort(document.querySelector('.table-wrap thead tr'), ST, ()=>{ ST.page=1; renderRows(); });
loadBookings();

/* ============ Add Booking modal ============ */
let CUST_MODE='existing';
function openBookingModal(){
  document.getElementById('bForm').reset();
  custMode('existing'); toggleDriver();
  document.getElementById('bEstimate').style.display='none';
  document.getElementById('bModal').classList.add('open');
}
function closeBookingModal(){ document.getElementById('bModal').classList.remove('open'); }
function custMode(m){
  CUST_MODE=m;
  document.getElementById('seg-existing').classList.toggle('active', m==='existing');
  document.getElementById('seg-walkin').classList.toggle('active', m==='walkin');
  document.getElementById('custExisting').style.display = m==='existing'?'block':'none';
  document.getElementById('custWalkin').style.display  = m==='walkin'?'block':'none';
}
function toggleDriver(){
  const on=document.getElementById('b_withDriver').checked;
  document.getElementById('driverWrap').style.display = on?'block':'none';
  estimate();
}
function daysBetween(a,b){ if(!a||!b) return 0; const d=(new Date(b)-new Date(a))/86400000; return d; }
function estimate(){
  const carOpt=document.getElementById('b_carId').selectedOptions[0];
  const price=carOpt?Number(carOpt.dataset.price||0):0;
  const unit=document.getElementById('b_rentalUnit').value;
  const p=document.getElementById('b_pickupDate').value, r=document.getElementById('b_returnDate').value;
  let qty=0;
  if(unit==='MONTH'){ const d=daysBetween(p,r); qty=Math.max(d>0?1:0, Math.round(d/30)); }
  else { qty=Math.max(0, Math.floor(daysBetween(p,r))); }
  if(!price||!qty){ document.getElementById('bEstimate').style.display='none'; return; }
  let total = unit==='MONTH' ? price*30*qty : price*qty;
  if(document.getElementById('b_withDriver').checked){
    const dOpt=document.getElementById('b_driverId').selectedOptions[0];
    const daily=dOpt?Number(dOpt.dataset.daily||0):0;
    total += (unit==='MONTH'? daily*30*qty : daily*qty);
  }
  document.getElementById('bEstimateVal').textContent=CUR+total.toLocaleString();
  document.getElementById('bEstimate').style.display='flex';
}
function sOrNull(id){ const v=document.getElementById(id).value.trim(); return v===''?null:v; }
function nOrNull(id){ const v=document.getElementById(id).value; return v===''?null:Number(v); }

function saveBooking(){
  const withDriver=document.getElementById('b_withDriver').checked;
  const payload={
    customerId: CUST_MODE==='existing'? nOrNull('b_customerId') : null,
    customerName: CUST_MODE==='walkin'? sOrNull('b_customerName') : null,
    customerPhone: CUST_MODE==='walkin'? sOrNull('b_customerPhone') : null,
    customerEmail: CUST_MODE==='walkin'? sOrNull('b_customerEmail') : null,
    carId: nOrNull('b_carId'),
    withDriver: withDriver,
    driverId: withDriver? nOrNull('b_driverId') : null,
    rentalUnit: document.getElementById('b_rentalUnit').value,
    pickupDate: sOrNull('b_pickupDate'),
    returnDate: sOrNull('b_returnDate'),
    pickupLocation: sOrNull('b_pickupLocation'),
    dropLocation: sOrNull('b_dropLocation')
  };
  // light client-side checks
  if(CUST_MODE==='existing' && !payload.customerId) return toast('Select a customer','err');
  if(CUST_MODE==='walkin' && !payload.customerName) return toast('Enter the walk-in customer name','err');
  if(!payload.carId) return toast('Select a car','err');
  if(!payload.pickupDate||!payload.returnDate) return toast('Choose pickup and return dates','err');
  if(withDriver && !payload.driverId) return toast('Select a driver','err');

  const btn=document.getElementById('bSaveBtn'); btn.disabled=true; btn.textContent='Creating…';
  const headers={'Content-Type':'application/json'}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API,{method:'POST',headers,body:JSON.stringify(payload)})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{
      if(res.ok&&res.body.ok){ closeBookingModal(); toast('Booking #'+res.body.id+' created','ok'); loadBookings(); }
      else toast(res.body.message||'Could not create booking','err');
    }).catch(()=>toast('Network error','err'))
    .finally(()=>{ btn.disabled=false; btn.textContent='Create Booking'; });
}

/* ============ Payments ============ */
let PAY_BK=null;
function openPayments(id){
  PAY_BK=id;
  document.getElementById('payBkTag').textContent='#'+id;
  document.getElementById('pay_amount').value=''; document.getElementById('pay_reference').value='';
  document.getElementById('pay_notes').value=''; document.getElementById('pay_paidAt').valueAsDate=new Date();
  document.getElementById('payModal').classList.add('open');
  loadPayments();
}
function closePayments(){ document.getElementById('payModal').classList.remove('open'); }
function loadPayments(){
  fetch(API+'/'+PAY_BK+'/payments').then(r=>r.json()).then(d=>{
    document.getElementById('paySumTotal').textContent=CUR+(d.total||0);
    document.getElementById('paySumPaid').textContent=CUR+(d.paid||0);
    document.getElementById('paySumBal').textContent=CUR+(d.balance||0);
    const tb=document.getElementById('payRows'); const list=d.payments||[];
    if(!list.length){ tb.innerHTML='<tr><td colspan="5" class="media-empty" style="background:none;border:none">No payments yet.</td></tr>'; return; }
    tb.innerHTML=list.map(p=>`
      <tr>
        <td>${p.paidAt||'—'}</td>
        <td>${esc((p.method||'').replace('_',' '))}</td>
        <td>${esc(p.reference)||'—'}</td>
        <td><strong>${CUR}${p.amount}</strong></td>
        <td><button class="icon-btn del" title="Delete" onclick="deletePayment(${p.id})">&#128465;</button></td>
      </tr>`).join('');
  });
}
function recordPayment(){
  const amount=document.getElementById('pay_amount').value;
  if(!amount||Number(amount)<=0) return toast('Enter a valid amount','err');
  const payload={ amount:Number(amount), method:document.getElementById('pay_method').value,
    reference:document.getElementById('pay_reference').value.trim()||null,
    paidAt:document.getElementById('pay_paidAt').value||null,
    notes:document.getElementById('pay_notes').value.trim()||null };
  const btn=document.getElementById('payAddBtn'); btn.disabled=true; btn.textContent='Saving…';
  const headers={'Content-Type':'application/json'}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/'+PAY_BK+'/payments',{method:'POST',headers,body:JSON.stringify(payload)})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ document.getElementById('pay_amount').value='';
        document.getElementById('pay_reference').value=''; document.getElementById('pay_notes').value='';
        toast('Payment recorded','ok'); loadPayments(); loadBookings(); }
      else toast(res.body.message||'Could not save','err'); })
    .catch(()=>toast('Network error','err'))
    .finally(()=>{ btn.disabled=false; btn.textContent='Add Payment'; });
}
function deletePayment(pid){
  if(!confirm('Delete this payment?'))return;
  const headers={}; headers[CSRF_HEADER]=CSRF_TOKEN;
  fetch(API+'/payments/'+pid+'/delete',{method:'POST',headers})
    .then(async r=>({ok:r.ok,body:await r.json()}))
    .then(res=>{ if(res.ok&&res.body.ok){ toast('Deleted','ok'); loadPayments(); loadBookings(); } else toast('Could not delete','err'); })
    .catch(()=>toast('Network error','err'));
}
document.getElementById('payModal').addEventListener('click',e=>{ if(e.target.id==='payModal') closePayments(); });

document.getElementById('bModal').addEventListener('click',e=>{ if(e.target.id==='bModal') closeBookingModal(); });
document.addEventListener('keydown',e=>{ if(e.key==='Escape'){ closeBookingModal(); closePayments(); } });
</script>

<footer th:replace="~{fragments/layout :: footer}"></footer>
</body>
</html>
