<?php /* cheques/pending.php */
$sym   = setting('currency_symbol','Rs.');
$today = date('Y-m-d');

$groups = [
  'overdue'  => ['label'=>'🔴 Overdue',   'data'=>$overdue,  'total'=>$totalOverdue,  'cls'=>'danger',  'hdr'=>'bg-danger text-white'],
  'today'    => ['label'=>'🟡 Due Today',  'data'=>$dueToday, 'total'=>$totalDueToday, 'cls'=>'warning', 'hdr'=>'bg-warning text-dark'],
  'upcoming' => ['label'=>'🔵 Upcoming',   'data'=>$upcoming, 'total'=>$totalUpcoming, 'cls'=>'primary', 'hdr'=>'bg-primary text-white'],
  'no_date'  => ['label'=>'⚪ No Date Set','data'=>$noDate,   'total'=>0,              'cls'=>'secondary','hdr'=>'bg-secondary text-white'],
];
?>

<style>
.pnd-hero{background:linear-gradient(135deg,#7c2d12,#dc2626 55%,#f97316);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.pnd-table th{font-size:.7rem;padding:7px 10px;white-space:nowrap}
.pnd-table td{font-size:.78rem;padding:6px 10px;vertical-align:middle}
</style>

<!-- Hero -->
<div class="pnd-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-hourglass-split me-2"></i>Pending Cheques</h5>
      <div style="opacity:.8;font-size:.82rem">
        <?= count($allPending) ?> cheques · Total <?= $sym ?><?= number_format($totalPending,2) ?> outstanding
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?= APP_URL ?>/cheques" class="btn btn-outline-light btn-sm">
        <i class="bi bi-arrow-left me-1"></i>All Cheques
      </a>
      <button onclick="window.print()" class="btn btn-light btn-sm fw-semibold" style="color:#dc2626">
        <i class="bi bi-printer me-1"></i>Print
      </button>
    </div>
  </div>
</div>

<?= flashMessages() ?>

<!-- Summary pills -->
<div class="row g-2 mb-4">
  <?php foreach($groups as $key=>$g):?>
  <?php if(empty($g['data'])) continue;?>
  <div class="col-6 col-md-3">
    <div class="card p-3 h-100" style="border-top:3px solid var(--bs-<?=$g['cls']?>)">
      <div class="fw-bold fs-5" style="color:var(--bs-<?=$g['cls']?>)"><?= $sym ?><?= number_format($g['total'],0) ?></div>
      <div class="small text-muted"><?= $g['label'] ?> (<?= count($g['data']) ?>)</div>
    </div>
  </div>
  <?php endforeach;?>
</div>

<!-- Cheque groups -->
<?php foreach($groups as $key=>$g):
  if(empty($g['data'])) continue;
?>
<div class="card mb-3">
  <div class="card-header <?= $g['hdr'] ?> fw-semibold d-flex justify-content-between align-items-center">
    <span><i class="bi bi-collection me-1"></i><?= $g['label'] ?> (<?= count($g['data']) ?>)</span>
    <span class="badge bg-white" style="color:var(--bs-<?=$g['cls']?>)">
      <?= $sym ?><?= number_format($g['total'],2) ?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 pnd-table">
      <thead class="table-secondary">
        <tr>
          <th class="ps-3">#</th>
          <th>Cheque No</th>
          <th>Party</th>
          <th>Bank</th>
          <th>Type</th>
          <th>Invoice</th>
          <th class="text-center">Due Date</th>
          <th class="text-end">Amount</th>
          <th class="text-center">Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($g['data'] as $i=>$c):?>
        <tr>
          <td class="ps-3 text-muted"><?=$i+1?></td>
          <td class="fw-bold" style="font-family:monospace"><?=e($c['cheque_no']??'—')?></td>
          <td>
            <div class="fw-semibold small"><?=e($c['party_name']??'—')?></div>
            <div style="font-size:.62rem;color:#94a3b8"><?=e($c['party_phone']??'')?></div>
          </td>
          <td class="small"><?=e($c['bank_name']??'—')?></td>
          <td>
            <span class="badge <?=$c['transaction_type']==='sale'?'bg-primary':'bg-info text-dark'?>" style="font-size:.6rem">
              <?=ucfirst($c['transaction_type'])?>
            </span>
          </td>
          <td class="small">
            <?php if($c['sale_invoice']):?>
            <a href="<?=APP_URL?>/sales/view/<?=$c['sale_id']?>"
               class="text-decoration-none fw-semibold text-primary">
              <?=e($c['sale_invoice'])?>
            </a>
            <?php elseif($c['purchase_invoice']):?>
            <span class="text-info"><?=e($c['purchase_invoice'])?></span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>
          <td class="text-center small">
            <?php if($c['cheque_date']):?>
            <span class="fw-semibold <?=$c['cheque_date']<$today?'text-danger':($c['cheque_date']===$today?'text-warning':'')?>">
              <?=date('d M Y',strtotime($c['cheque_date']))?>
            </span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>
          <td class="text-end fw-bold"><?=$sym?><?=number_format($c['amount'],2)?></td>
          <td class="text-center">
            <?php if(Auth::can('cheques.view')):?>
            <div class="d-flex gap-1 justify-content-center">
              <button class="btn btn-sm btn-success py-0 px-2 fw-semibold"
                      onclick="openModal(<?=$c['id']?>,'cleared','<?=e($c['cheque_no'])?>')">
                <i class="bi bi-check-lg"></i> Clear
              </button>
              <button class="btn btn-sm btn-outline-danger py-0 px-2"
                      onclick="openModal(<?=$c['id']?>,'bounced','<?=e($c['cheque_no'])?>')">
                <i class="bi bi-x-lg"></i>
              </button>
            </div>
            <?php endif;?>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>
      <tfoot class="table-secondary fw-bold" style="font-size:.72rem">
        <tr>
          <td colspan="7" class="ps-3">TOTAL (<?=count($g['data'])?>)</td>
          <td class="text-end"><?=$sym?><?=number_format($g['total'],2)?></td>
          <td></td>
        </tr>
      </tfoot>
    </table>
  </div>
</div>
<?php endforeach;?>

<?php if(empty($allPending)):?>
<div class="card">
  <div class="card-body text-center py-5 text-muted">
    <i class="bi bi-check-circle d-block fs-1 mb-2 text-success opacity-50"></i>
    <div class="fw-bold fs-5">All clear! No pending cheques.</div>
    <a href="<?=APP_URL?>/cheques" class="btn btn-outline-primary btn-sm mt-2">View All Cheques</a>
  </div>
</div>
<?php endif;?>

<!-- Modal -->
<div class="modal fade" id="statusModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px">
    <div class="modal-content">
      <div class="modal-header" id="mHeader">
        <h6 class="modal-title fw-bold" id="mTitle"></h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="mForm" method="POST">
        <?= Auth::csrfField() ?>
        <input type="hidden" name="status" id="mStatus">
        <div class="modal-body text-center">
          <div id="mIcon" style="font-size:3rem"></div>
          <div class="fw-semibold mt-2 mb-3" id="mMsg"></div>
          <div id="mDateGroup">
            <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>
          <textarea name="note" class="form-control mt-2" rows="2" placeholder="Note (optional)…"></textarea>
        </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="mBtn">Confirm</button>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
function openModal(id, status, no) {
  const APP='<?=APP_URL?>';
  document.getElementById('mForm').action=APP+'/cheques/status/'+id;
  document.getElementById('mStatus').value=status;
  if(status==='cleared'){
    document.getElementById('mHeader').className='modal-header bg-success text-white';
    document.getElementById('mTitle').textContent='Mark Cleared';
    document.getElementById('mIcon').textContent='✅';
    document.getElementById('mMsg').textContent='Cheque #'+no+' → CLEARED';
    document.getElementById('mBtn').className='btn btn-success fw-bold px-4';
    document.getElementById('mBtn').textContent='✅ Clear';
    document.getElementById('mDateGroup').style.display='block';
  } else {
    document.getElementById('mHeader').className='modal-header bg-danger text-white';
    document.getElementById('mTitle').textContent='Mark Bounced';
    document.getElementById('mIcon').textContent='❌';
    document.getElementById('mMsg').textContent='Cheque #'+no+' → BOUNCED (may reverse payment)';
    document.getElementById('mBtn').className='btn btn-danger fw-bold px-4';
    document.getElementById('mBtn').textContent='❌ Bounce';
    document.getElementById('mDateGroup').style.display='none';
  }
  new bootstrap.Modal(document.getElementById('statusModal')).show();
}
</script>