<?php
require_once __DIR__ . '/../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/layout.php';

$runId = (int)($_GET['id'] ?? 0);

if($runId <= 0){
    die("Invalid run");
}

/* LOAD RUN */
$stmt = $pdo->prepare("
    SELECT *
    FROM settlement_runs
    WHERE id = ? AND company_id = ?
    LIMIT 1
");

$stmt->execute([$runId, $_SESSION['company_id']]);
$run = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$run){
    die("Run not found");
}

/* LOAD RECORDS */
$stmt = $pdo->prepare("
    SELECT *
    FROM settlement_records
    WHERE run_id = ?
    ORDER BY department_code
");

$stmt->execute([$runId]);
$allRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rows = $allRows;

/* ===============================
   SEARCH + FILTER
================================= */

$search = $_GET['search'] ?? '';
$statusFilter = $_GET['status_filter'] ?? '';

/* FILTER */
if ($statusFilter !== '') {
    $rows = array_filter($rows, function($row) use ($statusFilter) {
        return $row['status'] === $statusFilter;
    });
}

/* SEARCH (ACROSS FULL DATASET) */
if ($search !== '') {
    $rows = array_filter($rows, function($row) use ($search) {
        $search = strtolower($search);
        return strpos(strtolower($row['department_full']), $search) !== false
            || strpos(strtolower($row['bank_account']), $search) !== false
            || strpos(strtolower($row['branch_code']), $search) !== false;
    });
}

/* ===============================
   TOTALS (FULL FILTERED DATA)
================================= */

$totalMonth = 0;
$totalCarry = 0;
$totalPayable = 0;

$readyTotal = 0;
$carryForwardTotal = 0;
$holdTotal = 0;
$mismatchTotal = 0;

foreach ($rows as $r) {

    $totalMonth += $r['month_total'];
    $totalCarry += $r['carry_in'];
    $totalPayable += $r['payable'];

    // STATUS TOTALS
    if ($r['status'] === 'READY') {
        $readyTotal += $r['payable'];
    }

    if ($r['status'] === 'CARRY_FORWARD') {
        $carryForwardTotal += $r['payable'];
    }

    if ($r['status'] === 'HOLD') {
        $holdTotal += $r['payable'];
    }

    if ($r['status'] === 'BANK_MISMATCH') {
        $mismatchTotal += $r['payable'];
    }
}
/* ===============================
   PAGINATION (AFTER TOTALS)
================================= */

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;

$totalRows = count($rows);
$totalPages = max(1, ceil($totalRows / $perPage));

$offset = ($page - 1) * $perPage;
$rows = array_slice($rows, $offset, $perPage);
?>

<div class="container">
    <div style="display:flex; gap:15px; margin-bottom:20px; flex-wrap:wrap;">

    <div style="background:#dff3e3; padding:15px; border-radius:8px; min-width:180px;">
        <strong>READY</strong><br>
        R <?= number_format($readyTotal,2) ?>
    </div>

    <div style="background:#fff2cc; padding:15px; border-radius:8px; min-width:180px;">
        <strong>CARRY</strong><br>
        R <?= number_format($carryForwardTotal,2) ?>
    </div>

    <div style="background:#f8d7da; padding:15px; border-radius:8px; min-width:180px;">
        <strong>HOLD</strong><br>
        R <?= number_format($holdTotal,2) ?>
    </div>

    <div style="background:#ffcccc; padding:15px; border-radius:8px; min-width:180px;">
        <strong>MISMATCH</strong><br>
        R <?= number_format($mismatchTotal,2) ?>
    </div>

</div>
    
<form method="get" style="margin-bottom:15px;">
    
    <input type="hidden" name="id" value="<?= $runId ?>">

    <input type="text" name="search" placeholder="Search Department / Bank"
           value="<?= htmlspecialchars($search) ?>">

    <select name="status_filter">
        <option value="">All Status</option>
        <option value="READY" <?= $statusFilter=='READY'?'selected':'' ?>>READY</option>
        <option value="CARRY_FORWARD" <?= $statusFilter=='CARRY_FORWARD'?'selected':'' ?>>CARRY</option>
        <option value="HOLD" <?= $statusFilter=='HOLD'?'selected':'' ?>>HOLD</option>
        <option value="BANK_MISMATCH" <?= $statusFilter=='BANK_MISMATCH'?'selected':'' ?>>MISMATCH</option>
    </select>

    <button type="submit">Filter</button>

</form>
<h2>Settlement Report #<?= $runId ?></h2>
<?php if ($run['status'] === 'DRAFT'): ?>
    <div style="margin-bottom:15px;">
        <a class="btn primary" href="process_final.php?run_id=<?= $runId ?>">
            🚀 Process Settlement
        </a>
    </div>
<?php else: ?>
    <div style="margin-bottom:15px;color:green;font-weight:bold;">
        ✅ Already Processed
    </div>
<?php endif; ?>

<div style="margin-bottom:15px;">
    <a class="btn" href="export_run.php?<?= http_build_query([
    'run_id' => $runId,
    'search' => $search,
    'status_filter' => $statusFilter
]) ?>">
        ⬇️ Download Netcash File
    </a>
</div>

<p><strong>File:</strong> <?= htmlspecialchars($run['file_name']) ?></p>
<p><strong>Date:</strong> <?= $run['created_at'] ?></p>

<div class="table-wrap">
<table>
<thead>
<tr>
    <th>Department</th>
    <th>Bank</th>
    <th>Branch</th>
    <th>Type</th>
    <th>Month Total</th>
    <th>Carry</th>
    <th>Payable</th>
    <th>Status</th>
</tr>
</thead>

<tbody>

<?php foreach ($rows as $row): ?>

<?php
$class = '';
if ($row['status']=='READY') $class='row-ready';
elseif ($row['status']=='CARRY_FORWARD') $class='row-carry';
elseif ($row['status']=='HOLD') $class='row-hold';
elseif ($row['status']=='BANK_MISMATCH') $class='row-mismatch';
?>

<tr class="<?= $class ?>">
    <td><?= htmlspecialchars($row['department_full']) ?></td>
    <td><?= htmlspecialchars($row['bank_account']) ?></td>
    <td><?= htmlspecialchars($row['branch_code']) ?></td>
    <td><?= htmlspecialchars($row['account_type']) ?></td>
    <td><?= number_format($row['month_total'],2) ?></td>
    <td><?= number_format($row['carry_in'],2) ?></td>
    <td><strong><?= number_format($row['payable'],2) ?></strong></td>
    <td><?= $row['status'] ?></td>
</tr>

<?php endforeach; ?>

<tr style="font-weight:bold;background:#f0f0f0;">
    <td colspan="4" style="text-align:right;">TOTAL:</td>
    <td><?= number_format($totalMonth,2) ?></td>
    <td><?= number_format($totalCarry,2) ?></td>
    <td><?= number_format($totalPayable,2) ?></td>
    <td></td>
</tr>

</tbody>
</table>
<div style="margin-top:15px;">
<?php for ($i = 1; $i <= $totalPages; $i++): ?>
    <a href="?<?= http_build_query(array_merge($_GET, ['page'=>$i])) ?>"
       style="padding:6px 10px;
              margin-right:5px;
              background:<?= $i==$page?'#333':'#ddd' ?>;
              color:<?= $i==$page?'#fff':'#000' ?>;
              text-decoration:none;">
        <?= $i ?>
    </a>
<?php endfor; ?>
</div>
</div>

</div>

<style>
.row-ready { background: #dff3e3; }
.row-carry { background: #fff2cc; }
.row-hold { background: #f8d7da; }
.row-mismatch { background: #ffcccc; }
</style>

<?php require_once __DIR__ . '/../../includes/layout_footer.php'; ?>