<?php /* cheques/index.php */
$sym = setting('currency_symbol','Rs.');
$statusCfg = [
  'pending' => ['bg-warning text-dark','⏳','#d97706'],
  'cleared' => ['bg-success','✅','#16a34a'],
  'bounced' => ['bg-danger','❌','#dc2626'],
];
$typeCfg = [
  'sale'     => ['bg-primary','bi-receipt','Sales Cheque'],
  'purchase' => ['bg-info text-dark','bi-truck','Purchase Cheque'],
];
$today = date('Y-m-d');
?>

<style>
.chq-hero{background:linear-gradient(135deg,#0f2557,#1e40af);border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-box{border-radius:10px;padding:14px 16px;text-align:center;height:100%}
.kpi-box .val{font-size:1.5rem;font-weight:900;line-height:1}
.kpi-box .lbl{font-size:.68rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.8}
.chq-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.chq-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.chq-table tr:hover td{background:#f8fafc}
.overdue-badge{animation:pulse 2s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.6}}
</style>

<!-- Hero -->
<div class="chq-hero">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div>
      <h5 class="fw-bold mb-1"><i class="bi bi-bank me-2"></i>Cheque Management</h5>
      <div style="opacity:.8;font-size:.82rem">
        Track sale & purchase cheques · Clear or bounce · Auto-updates balances
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?= APP_URL ?>/cheques/pending"
         class="btn btn-warning btn-sm fw-semibold text-dark">
        <i class="bi bi-hourglass-split me-1"></i>Pending
        <?php if($countPending>0):?>
        <span class="badge bg-dark ms-1"><?=$countPending?></span>
        <?php endif;?>
      </a>
      <button onclick="window.print()" class="btn btn-outline-light btn-sm">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- KPI Cards -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val" style="color:#d97706"><?= $sym ?><?= number_format($totalPending,0) ?></div>
      <div class="lbl" style="color:#d97706">⏳ Pending (<?=$countPending?>)</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?= $sym ?><?= number_format($overdueAmount,0) ?></div>
      <div class="lbl" style="color:#dc2626 ">🔴 Overdue (<?=$overdueCount?>)</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val" style="color:#16a34a"><?= $sym ?><?= number_format($totalCleared,0) ?></div>
      <div class="lbl" style="color:#16a34a">✅ Cleared</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-box" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val" style="color:#dc2626"><?= $sym ?><?= number_format($totalBounced,0) ?></div>
      <div class="lbl" style="color:#dc2626">❌ Bounced</div>
    </div>
  </div>
</div>

<!-- Sub-cards: Sale vs Purchase pending -->
<div class="row g-2 mb-3">
  <div class="col-md-4">
    <div class="card p-3 h-100" style="border-left:4px solid #3b82f6">
      <div class="small text-muted mb-1"><i class="bi bi-receipt me-1 text-primary"></i>Sale Cheques Pending</div>
      <div class="fw-bold fs-5 text-primary"><?= $sym ?><?= number_format($salePending,0) ?></div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card p-3 h-100" style="border-left:4px solid #0891b2">
      <div class="small text-muted mb-1"><i class="bi bi-truck me-1 text-info"></i>Purchase Cheques Pending</div>
      <div class="fw-bold fs-5 text-info"><?= $sym ?><?= number_format($purchasePending,0) ?></div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card p-3 h-100" style="border-left:4px solid #dc2626">
      <div class="small text-muted mb-1">
        <i class="bi bi-exclamation-octagon me-1 text-danger"></i>
        Overdue Cheques
      </div>
      <div class="fw-bold fs-5 text-danger">
        <?=$overdueCount?> cheque<?=$overdueCount!=1?'s':''?> · <?= $sym ?><?= number_format($overdueAmount,0) ?>
      </div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?= APP_URL ?>/cheques"
          class="d-flex gap-2 flex-wrap align-items-end">
      <div class="input-group input-group-sm" style="max-width:220px">
        <span class="input-group-text"><i class="bi bi-search"></i></span>
        <input type="text" name="search" class="form-control"
               placeholder="Cheque no, party, bank…"
               value="<?= e($search) ?>">
      </div>
      <select name="status" class="form-select form-select-sm" style="max-width:130px">
        <option value="all"    <?=$status==='all'?   'selected':''?>>All Status</option>
        <option value="pending"<?=$status==='pending'?'selected':''?>>⏳ Pending</option>
        <option value="cleared"<?=$status==='cleared'?'selected':''?>>✅ Cleared</option>
        <option value="bounced"<?=$status==='bounced'?'selected':''?>>❌ Bounced</option>
      </select>
      <select name="type" class="form-select form-select-sm" style="max-width:140px">
        <option value="all"     <?=$type==='all'?    'selected':''?>>All Types</option>
        <option value="sale"    <?=$type==='sale'?   'selected':''?>>🧾 Sales</option>
        <option value="purchase"<?=$type==='purchase'?'selected':''?>>🚚 Purchase</option>
      </select>
      <input type="date" name="from" class="form-control form-control-sm"
             value="<?= e($from) ?>" style="max-width:140px">
      <input type="date" name="to" class="form-control form-control-sm"
             value="<?= e($to) ?>" style="max-width:140px">
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?= APP_URL ?>/cheques" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
    </form>
  </div>
</div>

<!-- Cheques Table -->
<div class="card">
  <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
    <span class="fw-semibold small"><i class="bi bi-table me-1"></i>Cheques</span>
    <span class="badge bg-secondary"><?= count($cheques) ?> record<?= count($cheques)!=1?'s':''?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 chq-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Cheque No</th>
          <th>Type</th>
          <th>Party / Invoice</th>
          <th>Bank</th>
          <th class="text-center">Cheque Date</th>
          <th class="text-end">Amount</th>
          <th class="text-center">Status</th>
          <th class="text-center">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($cheques)):?>
        <tr>
          <td colspan="9" class="text-center text-muted py-5">
            <i class="bi bi-bank d-block fs-2 mb-2 opacity-25"></i>
            No cheques found for selected filters.
          </td>
        </tr>
        <?php endif;?>

        <?php foreach($cheques as $i=>$c):
          $stCfg  = $statusCfg[$c['status']] ?? ['bg-secondary','?','#64748b'];
          $tyCfg  = $typeCfg[$c['transaction_type']] ?? ['bg-secondary','bi-dot','Cheque'];
          $isOverdue = $c['status']==='pending' && !empty($c['cheque_date']) && $c['cheque_date'] < $today;
          $isDueToday= $c['status']==='pending' && !empty($c['cheque_date']) && $c['cheque_date'] === $today;
        ?>
        <tr class="<?= $isOverdue?'table-danger bg-opacity-25':($isDueToday?'table-warning bg-opacity-10':'') ?>">
          <td class="ps-3 text-muted small"><?= $i+1 ?></td>

          <!-- Cheque No -->
          <td>
            <div class="fw-bold" style="font-family:monospace;font-size:.82rem">
              <?= e($c['cheque_no'] ?: '—') ?>
            </div>
            <div style="font-size:.62rem;color:#94a3b8">
              <?= e($c['branch'] ?? '') ?>
            </div>
          </td>

          <!-- Type -->
          <td>
            <span class="badge <?= $tyCfg[0] ?>" style="font-size:.62rem">
              <i class="bi <?= $tyCfg[1] ?> me-1"></i><?= $tyCfg[2] ?>
            </span>
          </td>

          <!-- Party / Invoice -->
          <td>
            <div class="fw-semibold small"><?= e($c['party_name'] ?: $c['drawer'] ?: '—') ?></div>
            <div style="font-size:.65rem;color:#94a3b8">
              <?php if($c['sale_invoice']):?>
              <a href="<?= APP_URL ?>/sales/view/<?= $c['sale_id'] ?>"
                 class="text-primary text-decoration-none">
                <?= e($c['sale_invoice']) ?>
              </a>
              <?php elseif($c['purchase_invoice']):?>
              <span class="text-info"><?= e($c['purchase_invoice']) ?></span>
              <?php endif;?>
            </div>
          </td>

          <!-- Bank -->
          <td class="small">
            <div class="fw-semibold"><?= e($c['bank_name'] ?: '—') ?></div>
            <?php if($c['branch']&&$c['bank_name']!=$c['branch']):?>
            <div style="font-size:.65rem;color:#94a3b8"><?= e($c['branch']) ?></div>
            <?php endif;?>
          </td>

          <!-- Date -->
          <td class="text-center">
            <?php if($c['cheque_date']):?>
            <div class="fw-semibold small <?= $isOverdue?'text-danger overdue-badge':($isDueToday?'text-warning':'') ?>">
              <?= date('d M Y',strtotime($c['cheque_date'])) ?>
            </div>
            <?php if($isOverdue):?>
            <div class="text-danger" style="font-size:.6rem;font-weight:700">OVERDUE</div>
            <?php elseif($isDueToday):?>
            <div class="text-warning" style="font-size:.6rem;font-weight:700">DUE TODAY</div>
            <?php else:?>
            <div class="text-muted" style="font-size:.62rem">
              in <?= (int)((strtotime($c['cheque_date'])-time())/86400) ?> days
            </div>
            <?php endif;?>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Amount -->
          <td class="text-end fw-bold">
            <?= $sym ?><?= number_format($c['amount'],2) ?>
          </td>

          <!-- Status -->
          <td class="text-center">
            <span class="badge <?= $stCfg[0] ?>" style="font-size:.65rem">
              <?= $stCfg[1] ?> <?= ucfirst($c['status']) ?>
            </span>
            <?php if($c['cleared_date']):?>
            <div style="font-size:.6rem;color:#94a3b8">
              <?= date('d M',strtotime($c['cleared_date'])) ?>
            </div>
            <?php endif;?>
          </td>

          <!-- Actions -->
          <td class="text-center">
            <?php if($c['status']==='pending' && Auth::can('cheques.view')):?>
            <div class="d-flex gap-1 justify-content-center">
              <!-- Clear -->
              <button class="btn btn-sm btn-success py-0 px-2 fw-semibold"
                      onclick="openStatusModal(<?=$c['id']?>,'cleared','<?=e($c['cheque_no'])?>')"
                      title="Mark Cleared">
                <i class="bi bi-check-lg"></i> Clear
              </button>
              <!-- Bounce -->
              <button class="btn btn-sm btn-danger py-0 px-2"
                      onclick="openStatusModal(<?=$c['id']?>,'bounced','<?=e($c['cheque_no'])?>')"
                      title="Mark Bounced">
                <i class="bi bi-x-lg"></i>
              </button>
            </div>
            <?php else:?>
            <span class="text-muted small"><?=$c['status']==='pending'?'—':ucfirst($c['status'])?></span>
            <?php endif;?>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <!-- Summary footer -->
      <?php if(!empty($cheques)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="6" class="ps-3">TOTAL (<?=count($cheques)?> cheques)</td>
          <td class="text-end"><?=$sym?><?=number_format(array_sum(array_column($cheques,'amount')),2)?></td>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>
</div>

<!-- Status Update Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:420px">
    <div class="modal-content">
      <div class="modal-header" id="statusModalHeader">
        <h6 class="modal-title fw-bold" id="statusModalTitle">Update Cheque</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="statusForm" method="POST">
        <?= Auth::csrfField() ?>
        <input type="hidden" name="status" id="statusInput">
        <div class="modal-body">
          <div class="mb-3 text-center">
            <div id="statusIcon" style="font-size:3rem"></div>
            <div class="fw-semibold mt-2" id="statusMsg"></div>
          </div>
          <div id="clearedDateGroup" class="mb-3" style="display:none">
            <label class="form-label small fw-semibold">Cleared Date</label>
            <input type="date" name="cleared_date" class="form-control"
                   value="<?= date('Y-m-d') ?>">
          </div>
          <div class="mb-3">
            <label class="form-label small fw-semibold">Note (optional)</label>
            <textarea name="note" class="form-control" rows="2"
                      placeholder="Add a note…"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn fw-bold px-4" id="statusSubmitBtn">Confirm</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function openStatusModal(id, status, chequeNo) {
  const form   = document.getElementById('statusForm');
  const header = document.getElementById('statusModalHeader');
  const title  = document.getElementById('statusModalTitle');
  const icon   = document.getElementById('statusIcon');
  const msg    = document.getElementById('statusMsg');
  const btn    = document.getElementById('statusSubmitBtn');
  const cdg    = document.getElementById('clearedDateGroup');

  form.action = '<?= APP_URL ?>/cheques/status/' + id;
  document.getElementById('statusInput').value = status;

  if (status === 'cleared') {
    header.className    = 'modal-header bg-success text-white';
    title.textContent   = 'Mark Cheque as Cleared';
    icon.textContent    = '✅';
    msg.textContent     = `Cheque #${chequeNo} will be marked as CLEARED.`;
    btn.className       = 'btn btn-success fw-bold px-4';
    btn.textContent     = '✅ Mark Cleared';
    cdg.style.display   = 'block';
  } else {
    header.className    = 'modal-header bg-danger text-white';
    title.textContent   = 'Mark Cheque as Bounced';
    icon.textContent    = '❌';
    msg.textContent     = `Cheque #${chequeNo} will be marked as BOUNCED. This may reverse the payment.`;
    btn.className       = 'btn btn-danger fw-bold px-4';
    btn.textContent     = '❌ Mark Bounced';
    cdg.style.display   = 'none';
  }
  new bootstrap.Modal(document.getElementById('statusModal')).show();
}
</script>