<?php /* stock/movements.php */
$sym      = setting('currency_symbol','Rs.');
$data     = $pagination['data'];
$lastPage = $pagination['pages'];
$curPage  = $pagination['current'];
$perPage  = $pagination['perPage'];

$typeConfig = [
  'sale'       => ['bg-primary',              'bi-receipt',           '#1d4ed8', 'Sale'],
  'purchase'   => ['bg-success',              'bi-cart-fill',         '#16a34a', 'Purchase'],
  'adjustment' => ['bg-warning text-dark',    'bi-sliders',           '#d97706', 'Adjustment'],
  'return'     => ['bg-info text-dark',       'bi-arrow-return-left', '#0891b2', 'Return'],
  'damage'     => ['bg-danger',               'bi-exclamation-octagon','#dc2626','Damage'],
  'opening'    => ['bg-secondary',            'bi-box-seam',          '#64748b', 'Opening'],
  'transfer'   => ['bg-purple text-white',    'bi-arrow-left-right',  '#7c3aed', 'Transfer'],
];
$selectedProduct = null;
if ($productId) {
    foreach ($products as $p) {
        if ($p['id'] == $productId) { $selectedProduct = $p; break; }
    }
}
?>

<style>
.sm-hero{background:linear-gradient(135deg,#1e3a5f,#0891b2 60%,#06b6d4);
  border-radius:12px;padding:20px 26px;color:#fff;margin-bottom:18px}
.kpi-pill{border-radius:10px;padding:12px 14px;text-align:center;height:100%}
.kpi-pill .val{font-size:1.3rem;font-weight:900;line-height:1}
.kpi-pill .lbl{font-size:.63rem;text-transform:uppercase;letter-spacing:.05em;margin-top:3px;opacity:.85}
.sm-table th{font-size:.7rem;padding:8px 10px;white-space:nowrap}
.sm-table td{font-size:.78rem;padding:7px 10px;vertical-align:middle}
.sm-table tr:hover td{background:#f0f9ff}
.mv-badge{display:inline-flex;align-items:center;gap:3px;padding:2px 8px;
  border-radius:10px;font-size:.63rem;font-weight:700;white-space:nowrap}
.stock-change{font-size:.85rem;font-weight:900;padding:2px 8px;border-radius:8px}
</style>

<!-- Hero -->
<div class="sm-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-arrow-left-right me-2"></i>Stock Movements
      </h5>
      <div style="opacity:.8;font-size:.82rem">
        <?php if($selectedProduct):?>
        <strong><?=e($selectedProduct['product_name'])?></strong>
        (<?=e($selectedProduct['product_code'])?>)
        &nbsp;·&nbsp;
        <?php endif;?>
        <?=date('d M Y',strtotime($from))?> – <?=date('d M Y',strtotime($to))?>
        &nbsp;·&nbsp; <?=number_format($summary['total_rows'])?> movements
      </div>
    </div>
    <div class="d-flex gap-2">
      <a href="<?=APP_URL?>/stock" class="btn btn-outline-light btn-sm">
        <i class="bi bi-layers me-1"></i>Stock Register
      </a>
      <?php if(Auth::can('stock.manage')):?>
      <a href="<?=APP_URL?>/stock/adjust"
         class="btn btn-light btn-sm fw-semibold" style="color:#0891b2">
        <i class="bi bi-sliders me-1"></i>Adjust Stock
      </a>
      <?php endif;?>
      <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 Pills -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0fdf4;border:2px solid #16a34a">
      <div class="val text-success">+<?=number_format($summary['total_in'],2)?></div>
      <div class="lbl text-success">Total Stock In</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef2f2;border:2px solid #dc2626">
      <div class="val text-danger">-<?=number_format($summary['total_out'],2)?></div>
      <div class="lbl text-danger">Total Stock Out</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#f0f9ff;border:2px solid #0891b2">
      <?php $net = (float)$summary['total_in'] - (float)$summary['total_out']; ?>
      <div class="val" style="color:<?=$net>=0?'#0891b2':'#dc2626'?>">
        <?=($net>=0?'+':'').number_format($net,2)?>
      </div>
      <div class="lbl" style="color:#0891b2">Net Movement</div>
    </div>
  </div>
  <div class="col-6 col-md-3">
    <div class="kpi-pill" style="background:#fef9c3;border:2px solid #d97706">
      <div class="val text-warning"><?=number_format($summary['total_rows'])?></div>
      <div class="lbl text-warning">Total Movements</div>
    </div>
  </div>
</div>

<!-- Filters -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" action="<?=APP_URL?>/stock/movements"
          class="d-flex gap-2 flex-wrap align-items-end">
      <!-- Date range -->
      <div class="d-flex gap-1 align-items-center">
        <input type="date" name="from" class="form-control form-control-sm"
               value="<?=e($from)?>" style="width:135px">
        <span class="text-muted small">to</span>
        <input type="date" name="to" class="form-control form-control-sm"
               value="<?=e($to)?>" style="width:135px">
      </div>
      <!-- Product -->
      <select name="product_id" class="form-select form-select-sm" style="max-width:200px">
        <option value="0">All Products</option>
        <?php foreach($products as $p):?>
        <option value="<?=$p['id']?>" <?=$productId==$p['id']?'selected':''?>>
          <?=e($p['product_name'])?> (<?=e($p['product_code'])?>)
        </option>
        <?php endforeach;?>
      </select>
      <!-- Type -->
      <select name="type" class="form-select form-select-sm" style="max-width:140px">
        <option value="all" <?=$typeF==='all'?'selected':''?>>All Types</option>
        <?php foreach($movTypes as $mt):
          $tc = $typeConfig[$mt['movement_type']]??['','','#64748b',ucfirst($mt['movement_type'])];
        ?>
        <option value="<?=e($mt['movement_type'])?>"
                <?=$typeF===$mt['movement_type']?'selected':''?>>
          <?=$tc[3]?>
        </option>
        <?php endforeach;?>
      </select>
      <button class="btn btn-secondary btn-sm fw-semibold">
        <i class="bi bi-funnel me-1"></i>Filter
      </button>
      <a href="<?=APP_URL?>/stock/movements" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-x-lg"></i>
      </a>
      <!-- Quick shortcuts -->
      <div class="d-flex gap-1">
        <?php foreach([
          'Today'     =>[date('Y-m-d'),     date('Y-m-d')],
          'This Week' =>[date('Y-m-d',strtotime('monday this week')),date('Y-m-d')],
          'This Month'=>[date('Y-m-01'),     date('Y-m-d')],
        ] as $lbl=>[$f,$t]):
          $isAct=($from===$f&&$to===$t);
        ?>
        <a href="?from=<?=$f?>&to=<?=$t?><?=$productId?"&product_id=$productId":''?>"
           class="btn btn-sm <?=$isAct?'btn-info text-white':'btn-outline-secondary'?>">
          <?=$lbl?>
        </a>
        <?php endforeach;?>
      </div>
    </form>
  </div>
</div>

<!-- Movements 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-arrow-left-right me-1"></i>Movement History
    </span>
    <span class="badge bg-secondary">
      <?=number_format($pagination['total'])?> records · Page <?=$curPage?>/<?=$lastPage?>
    </span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm table-hover mb-0 sm-table">
      <thead class="table-dark">
        <tr>
          <th class="ps-3">#</th>
          <th>Product</th>
          <th class="text-center">Type</th>
          <th class="text-center text-success">Stock In</th>
          <th class="text-center text-danger">Stock Out</th>
          <th class="text-center">After</th>
          <th>Reference</th>
          <th>Note</th>
          <th class="text-center">Date / By</th>
        </tr>
      </thead>
      <tbody>
        <?php if(empty($data)):?>
        <tr>
          <td colspan="9" class="text-center text-muted py-5">
            <i class="bi bi-arrow-left-right d-block fs-2 mb-2 opacity-25"></i>
            No stock movements found for selected filters.
          </td>
        </tr>
        <?php endif;?>

        <?php
        $rowNum = ($curPage-1)*$perPage;
        foreach($data as $row):
          $rowNum++;
          $tc    = $typeConfig[$row['movement_type']] ?? ['bg-secondary','bi-dot','#64748b',ucfirst($row['movement_type'])];
          $isIn  = (float)$row['quantity_in']  > 0;
          $isOut = (float)$row['quantity_out'] > 0;
        ?>
        <tr>
          <td class="ps-3 text-muted small"><?=$rowNum?></td>

          <!-- Product -->
          <td>
            <a href="<?=APP_URL?>/stock/movements/<?=$row['product_id']?>"
               class="fw-semibold text-decoration-none text-dark">
              <?=e($row['product_name'])?>
            </a>
            <div style="font-size:.63rem;color:#94a3b8">
              <code><?=e($row['product_code'])?></code>
            </div>
          </td>

          <!-- Type -->
          <td class="text-center">
            <span class="mv-badge <?=$tc[0]?>">
              <i class="bi <?=$tc[1]?>"></i>
              <?=$tc[3]?>
            </span>
          </td>

          <!-- Stock In -->
          <td class="text-center">
            <?php if($isIn):?>
            <span class="stock-change"
                  style="background:#f0fdf4;color:#16a34a">
              +<?=number_format((float)$row['quantity_in'],2)?>
            </span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Stock Out -->
          <td class="text-center">
            <?php if($isOut):?>
            <span class="stock-change"
                  style="background:#fef2f2;color:#dc2626">
              -<?=number_format((float)$row['quantity_out'],2)?>
            </span>
            <?php else:?>
            <span class="text-muted">—</span>
            <?php endif;?>
          </td>

          <!-- Stock After -->
          <td class="text-center">
            <span class="fw-bold"
                  style="color:<?=(float)$row['stock_after']<=0?'#dc2626':
                               ((float)$row['stock_after']<5?'#d97706':'#16a34a')?>">
              <?=number_format((float)$row['stock_after'],2)?>
            </span>
          </td>

          <!-- Reference -->
          <td>
            <?php if($row['reference_no']):?>
            <code style="font-size:.7rem;color:#475569">
              <?=e($row['reference_no'])?>
            </code>
            <?php else:?>
            <span class="text-muted small">—</span>
            <?php endif;?>
          </td>

          <!-- Note -->
          <td>
            <div class="text-muted"
                 style="font-size:.72rem;max-width:160px;overflow:hidden;
                        text-overflow:ellipsis;white-space:nowrap"
                 title="<?=e($row['note']??'')?>">
              <?=e(substr($row['note']??'',0,40))?><?=strlen($row['note']??'')>40?'…':''?>
            </div>
          </td>

          <!-- Date / By -->
          <td class="text-center">
            <div class="small fw-semibold">
              <?=date('d M Y',strtotime($row['created_at']))?>
            </div>
            <div style="font-size:.63rem;color:#94a3b8">
              <?=date('H:i',strtotime($row['created_at']))?>
              <?php if($row['user_name']):?>
              · <?=e($row['user_name'])?>
              <?php endif;?>
            </div>
          </td>
        </tr>
        <?php endforeach;?>
      </tbody>

      <?php if(!empty($data)):?>
      <tfoot class="table-secondary fw-bold" style="font-size:.75rem">
        <tr>
          <td colspan="3" class="ps-3">PAGE TOTAL (<?=count($data)?> rows)</td>
          <td class="text-center text-success">
            +<?=number_format(array_sum(array_column($data,'quantity_in')),2)?>
          </td>
          <td class="text-center text-danger">
            -<?=number_format(array_sum(array_column($data,'quantity_out')),2)?>
          </td>
          <td colspan="4"></td>
        </tr>
      </tfoot>
      <?php endif;?>
    </table>
  </div>

  <!-- Pagination -->
  <?php if($lastPage > 1):?>
  <div class="card-footer d-flex justify-content-between align-items-center py-2">
    <span class="text-muted small">
      Page <?=$curPage?> of <?=$lastPage?>
      · <?=number_format($pagination['total'])?> total movements
    </span>
    <nav>
      <ul class="pagination pagination-sm mb-0">
        <li class="page-item <?=$curPage<=1?'disabled':''?>">
          <a class="page-link"
             href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage-1]))?>">‹</a>
        </li>
        <?php foreach(range(max(1,$curPage-2),min($lastPage,$curPage+2)) as $p):?>
        <li class="page-item <?=$p===$curPage?'active':''?>">
          <a class="page-link"
             href="?<?=http_build_query(array_merge($_GET,['page'=>$p]))?>"><?=$p?></a>
        </li>
        <?php endforeach;?>
        <li class="page-item <?=$curPage>=$lastPage?'disabled':''?>">
          <a class="page-link"
             href="?<?=http_build_query(array_merge($_GET,['page'=>$curPage+1]))?>">›</a>
        </li>
      </ul>
    </nav>
  </div>
  <?php endif;?>
</div>