<?php
// ============================================================
//  MediCore — Requisition Record
//  File: product/req-record.php
// ============================================================
$page  = 'product/req-record';
$title = 'Requisition Record';
require_once '../includes/header.php';
require_once '../includes/requisition-tabs.php';

$cur = $settings['currency'];

$total      = (int)   db_val("SELECT COUNT(*) FROM requisitions");
$active     = (int)   db_val("SELECT COUNT(*) FROM requisitions WHERE status='active'");
$ordered    = (int)   db_val("SELECT COUNT(*) FROM requisitions WHERE status='ordered'");
$received   = (int)   db_val("SELECT COUNT(*) FROM requisitions WHERE status='received'");
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch" placeholder="🔍  REQ# or supplier…"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;width:190px;outline:none">
  <select id="f-status" onchange="load()"
    style="padding:5px 9px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none">
    <option value="">All Status</option>
    <option value="active">Active</option>
    <option value="ordered">Ordered</option>
    <option value="received">Received</option>
    <option value="cancelled">Cancelled</option>
  </select>
  <a class="btn btn-primary btn-sm" href="requisition.php">
    ➕ New Requisition
  </a>`;
</script>

<!-- ── Summary cards ──────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);
            gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Total REQs</div>
    <div class="sval b"><?= $total ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--warn)">
    <div class="slabel">Active</div>
    <div class="sval b" style="color:var(--warn)"><?= $active ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--brand)">
    <div class="slabel">Ordered</div>
    <div class="sval b" style="color:var(--brand)"><?= $ordered ?></div>
  </div>
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Received</div>
    <div class="sval b" style="color:var(--accent)"><?= $received ?></div>
  </div>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table>
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>REQ Number</th>
          <th>Supplier</th>
          <th>Date</th>
          <th style="text-align:center">Items</th>
          <th style="text-align:right">Total Value</th>
          <th style="text-align:center">Status</th>
          <th style="text-align:center;width:200px">Actions</th>
        </tr>
      </thead>
      <tbody id="req-body">
        <tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="req-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API      = '../api/requisitions.php';
const CUR      = '<?= addslashes($cur) ?>';
const IS_ADMIN = <?= is_admin() ? 'true' : 'false' ?>;
let timer      = null;

const STATUS_CFG = {
  active:    { bg:'#fff3dc', cl:'var(--warn)',   label:'Active'    },
  ordered:   { bg:'var(--brand-xlight)', cl:'var(--brand)',  label:'Ordered'   },
  received:  { bg:'#d4f0e6', cl:'var(--accent)', label:'Received'  },
  cancelled: { bg:'var(--surface2)', cl:'var(--text3)',  label:'Cancelled' },
};

// ── Load ──────────────────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('req-body');
  tbody.innerHTML =
    '<tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>';

  const r = await apiPost(API, {
    action: 'list',
    q:      document.getElementById('srch')?.value.trim()  || '',
    status: document.getElementById('f-status')?.value     || '',
  });

  if (!r.success) {
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state"
      style="color:var(--danger)">Error: ${r.error}</td></tr>`;
    return;
  }

  const rows   = r.data;
  const footer = document.getElementById('req-footer');
  footer.textContent = `Showing ${rows.length} requisition(s)`;

  if (!rows.length) {
    tbody.innerHTML =
      '<tr><td colspan="8" class="empty-state">No requisitions found.</td></tr>';
    return;
  }

  tbody.innerHTML = rows.map((req, i) => {
    const st  = STATUS_CFG[req.status] || STATUS_CFG.active;
    const val = parseFloat(req.total_price || 0);

    return `<tr data-id="${req.id}">
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <span class="mono"
              style="font-weight:700;color:var(--brand);cursor:pointer"
              onclick="viewDetail(${req.id})">
          ${esc(req.ref)}
        </span>
      </td>
      <td style="font-weight:500">${esc(req.supplier_name || '—')}</td>
      <td style="color:var(--text2)">${req.date || '—'}</td>
      <td style="text-align:center">
        <span class="badge"
              style="background:var(--surface2);color:var(--text2)">
          ${req.item_count}
        </span>
      </td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${val > 0 ? CUR + val.toFixed(2) : '—'}
      </td>
      <td style="text-align:center">
        <span class="badge"
              style="background:${st.bg};color:${st.cl};font-weight:700">
          ${st.label}
        </span>
      </td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"
                onclick="viewDetail(${req.id})">🔍 View</button>
        ${req.status !== 'received' && req.status !== 'cancelled'
          ? `<button class="btn btn-sm btn-primary"
                     onclick="openGeneratePO(${req.id},'${esc(req.ref).replace(/'/g,"\\'")}','${esc(req.supplier_name||'').replace(/'/g,"\\'")}')">
               📦 Gen PO
             </button>`
          : ''}
        <select class="btn btn-sm"
                style="padding:3px 6px;font-size:11px"
                onchange="updateStatus(${req.id},this.value)"
                title="Change status">
          <option value="">Status ▾</option>
          <option value="active"   >Active</option>
          <option value="ordered"  >Ordered</option>
          <option value="received" >Received</option>
          <option value="cancelled">Cancelled</option>
        </select>
        ${IS_ADMIN
          ? `<button class="btn btn-sm btn-danger"
                     onclick="delReq(${req.id},'${esc(req.ref).replace(/'/g,"\\'")}')">
               🗑</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');
}

// ── View detail ───────────────────────────────────────────────
async function viewDetail(id) {
  showModal(
    `<div style="text-align:center;padding:20px;color:var(--text3)">⏳ Loading…</div>`,
    '🔍 Requisition Detail', 'xl'
  );

  const r = await apiPost(API, { action: 'detail', id });
  if (!r.success) {
    document.querySelector('.mbox').innerHTML =
      `<div style="padding:20px;color:var(--danger)">Error: ${r.error}</div>`;
    return;
  }

  const req   = r.data;
  const items = r.items || [];
  const st    = STATUS_CFG[req.status] || STATUS_CFG.active;

  const itemRows = items.map((it, i) => {
    const stockBg = parseInt(it.stock_pcs) <= 0 ? '#fde8e8'
      : parseInt(it.stock_pcs) < 10 ? '#fff3dc' : '#d4f0e6';
    const stockCl = parseInt(it.stock_pcs) <= 0 ? 'var(--danger)'
      : parseInt(it.stock_pcs) < 10 ? 'var(--warn)' : 'var(--accent)';

    return `<tr>
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <div style="font-weight:600;font-size:12px">${formIconName(it.form, it.product_name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${it.strength||''} ${it.form ? '· '+it.form : ''}
          ${it.rack ? '· Rack: '+esc(it.rack) : ''}
        </div>
      </td>
      <td style="text-align:center">
        <span class="badge" style="background:${stockBg};color:${stockCl}">
          ${it.stock_pcs}
        </span>
      </td>
      <td class="mono" style="text-align:center;font-weight:700">${it.qty_box}</td>
      <td class="mono" style="text-align:right">
        ${parseFloat(it.btp_vat||0) > 0
          ? CUR + parseFloat(it.btp_vat).toFixed(2)
          : '<span style="color:var(--text3)">—</span>'}
      </td>
      <td class="mono" style="text-align:right;font-weight:700">
        ${parseFloat(it.total_price||0) > 0
          ? CUR + parseFloat(it.total_price).toFixed(2)
          : '—'}
      </td>
    </tr>`;
  }).join('');

  document.querySelector('.mbox').innerHTML = `
    <div class="mtitle">
      📝 REQ:
      <span class="mono" style="color:var(--brand)">${esc(req.ref)}</span>
      <button class="mclose" onclick="closeModal()">×</button>
    </div>
    <!-- Header -->
    <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;
                padding:10px 14px;border-bottom:1px solid var(--border)">
      <div>
        <div style="font-size:10px;color:var(--text3)">Supplier</div>
        <div style="font-weight:700">${esc(req.supplier_name||'—')}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Date</div>
        <div style="font-weight:600">${req.date||'—'}</div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Status</div>
        <div>
          <span class="badge"
                style="background:${st.bg};color:${st.cl};font-weight:700">
            ${st.label}
          </span>
        </div>
      </div>
      <div>
        <div style="font-size:10px;color:var(--text3)">Total Value</div>
        <div class="mono" style="font-weight:700;color:var(--brand)">
          ${parseFloat(req.total_price||0) > 0
            ? CUR + parseFloat(req.total_price).toFixed(2) : '—'}
        </div>
      </div>
    </div>
    <!-- Items -->
    <div class="tw" style="max-height:340px;overflow-y:auto">
      <table>
        <thead><tr>
          <th>#</th><th>Product</th>
          <th style="text-align:center">Stock</th>
          <th style="text-align:center">Req. Boxes</th>
          <th style="text-align:right">TP+VAT</th>
          <th style="text-align:right">Total</th>
        </tr></thead>
        <tbody>${itemRows}</tbody>
      </table>
    </div>
    ${req.notes
      ? `<div style="padding:8px 14px;font-size:11.5px;color:var(--text2);
                     border-top:1px solid var(--border)">
           📝 ${esc(req.notes)}</div>`
      : ''}
    <div style="padding:10px 14px;display:flex;gap:8px;justify-content:flex-end">
      <button class="btn" onclick="closeModal()">Close</button>
    </div>`;
}

// ── Update status ─────────────────────────────────────────────
async function updateStatus(id, status) {
  if (!status) return;
  const r = await apiPost(API, { action: 'update_status', id, status });
  if (r.success) load();
  else alert('⚠ ' + (r.error || 'Update failed.'));
}

// ── Generate PO modal ────────────────────────────────────────
function openGeneratePO(reqId, ref, supplier) {
  showModal(`
  <div style="margin-bottom:12px">
    <div style="font-size:11px;color:var(--text2)">Requisition</div>
    <div class="mono" style="font-weight:700;font-size:15px;color:var(--brand)">${esc(ref)}</div>
    <div style="font-size:12px;color:var(--text2);margin-top:4px">
      Supplier: <strong>${esc(supplier)}</strong>
    </div>
  </div>

  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Purchase Calculation Mode *</label>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
        <label id="lbl-tpvat"
               style="display:flex;align-items:flex-start;gap:7px;
                      padding:10px 12px;border:2px solid var(--brand);
                      border-radius:var(--rsm);cursor:pointer;
                      background:var(--brand-xlight)">
          <input type="radio" name="po-mode" value="unit_trvat" checked
                 onchange="hlPoMode()">
          <div>
            <div style="font-weight:700;color:var(--brand)">TP + VAT Mode</div>
            <div style="font-size:10px;color:var(--text3);margin-top:2px">
              Enter Trade Price and VAT separately. VAT shown on PO.
            </div>
          </div>
        </label>
        <label id="lbl-net"
               style="display:flex;align-items:flex-start;gap:7px;
                      padding:10px 12px;border:2px solid var(--border);
                      border-radius:var(--rsm);cursor:pointer">
          <input type="radio" name="po-mode" value="net_value"
                 onchange="hlPoMode()">
          <div>
            <div style="font-weight:700">Net Value Mode</div>
            <div style="font-size:10px;color:var(--text3);margin-top:2px">
              Enter combined net price. No separate VAT.
            </div>
          </div>
        </label>
      </div>
    </div>
    <div id="po-err" style="color:var(--danger);font-size:11px;display:none"></div>
  </div>

  <div style="display:flex;gap:8px;justify-content:flex-end;margin-top:14px;
              padding-top:12px;border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-primary" onclick="doGeneratePO(${reqId})">
      📦 Generate Purchase Order →
    </button>
  </div>`, `📦 Generate PO — ${esc(ref)}`);
  setTimeout(hlPoMode, 50);
}

function hlPoMode() {
  const isTP = document.querySelector('input[name="po-mode"][value="unit_trvat"]')?.checked;
  const lblT = document.getElementById('lbl-tpvat');
  const lblN = document.getElementById('lbl-net');
  if (lblT) {
    lblT.style.borderColor  = isTP ? 'var(--brand)' : 'var(--border)';
    lblT.style.background   = isTP ? 'var(--brand-xlight)' : 'transparent';
  }
  if (lblN) {
    lblN.style.borderColor  = !isTP ? 'var(--brand)' : 'var(--border)';
    lblN.style.background   = !isTP ? 'var(--brand-xlight)' : 'transparent';
  }
}

async function doGeneratePO(reqId) {
  const mode  = document.querySelector('input[name="po-mode"]:checked')?.value || 'unit_trvat';
  const errEl = document.getElementById('po-err');
  const btn   = document.querySelector('[onclick="doGeneratePO('+reqId+')"]');
  if (btn) { btn.disabled = true; btn.textContent = '⏳ Preparing…'; }

  const r = await apiPost(API, { action: 'generate_po', req_id: reqId, mode });

  if (r.success) {
    closeModal();
    // Redirect to purchase entry pre-filled from session
    window.location.href = r.redirect;
  } else {
    if (btn) { btn.disabled = false; btn.textContent = '📦 Generate Purchase Order →'; }
    errEl.textContent   = '⚠ ' + (r.error || 'Failed');
    errEl.style.display = 'block';
  }
}

// ── Delete ────────────────────────────────────────────────────
async function delReq(id, ref) {
  if (!confirm(`Delete requisition "${ref}"?\nThis cannot be undone.`)) return;
  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) load();
  else alert('⚠ ' + (r.error || 'Delete failed.'));
}

// ── Search ────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  load();
  const s = document.getElementById('srch');
  s.addEventListener('input', () => {
    clearTimeout(timer); timer = setTimeout(load, 280);
  });
});

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
</script>

<?php require_once '../includes/footer.php'; ?>