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

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

if (!isset($_SESSION['settlement_preview'])) {
    die("No settlement data found. Upload a CSV first.");
}

$results = $_SESSION['settlement_preview'];
$fileName = $_SESSION['settlement_filename'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_settlement'])) {

    $companyId = $_SESSION['company_id'];
    $userId    = $_SESSION['user_id'];

    // TOTALS
    $totalAmount = 0;
    foreach ($results as $r) {
        $totalAmount += (float)$r['payable'];
    }

    // SAVE RUN
    $stmt = $pdo->prepare("
    INSERT INTO settlement_runs 
    (company_id, file_name, total_records, total_amount, created_by, period_start, period_end, status)
    VALUES (?,?,?,?,?,?,?,?)
");

$stmt->execute([
    $companyId,
    $fileName,
    count($results),
    $totalAmount,
    $userId,
    $_SESSION['settlement_period_start'],
    $_SESSION['settlement_period_end'],
    'DRAFT'
]);

    $runId = $pdo->lastInsertId();

    // SAVE RECORDS
    $stmt = $pdo->prepare("
        INSERT INTO settlement_records
        (run_id, department_code, department_full, bank_account, branch_code, account_type,
         month_total, carry_in, payable, status, db_bank, db_branch)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
    ");

    foreach ($results as $row) {

        $stmt->execute([
            $runId,
            $row['department_code'],
            $row['department_full'],
            $row['bank'],
            $row['branch'],
            $row['type'],
            $row['month_total'],
            $row['carry_in'],
            $row['payable'],
            $row['status'],
            $row['db_bank'],
            $row['db_branch']
        ]);
    }

    header("Location: history.php?saved=1");
    exit;
}
$fileName = $_SESSION['settlement_filename'] ?? '';

$filterStatus = $_GET['status'] ?? '';
$sortColumn   = $_GET['sort'] ?? '';
$sortDir      = $_GET['dir'] ?? 'asc';

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

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

/* ===============================
   HANDLE CSV BANK CORRECTION
================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_bank'])) {

    $dept = $_POST['update_bank'];
    $newBank = trim($_POST['bank'][$dept] ?? '');
    $newBranch = trim($_POST['branch'][$dept] ?? '');

    if ($newBank !== '' && $newBranch !== '') {

        foreach ($_SESSION['settlement_preview'] as &$row) {

            if ($row['department_code'] === $dept) {

                $row['bank'] = $newBank;
                $row['branch'] = $newBranch;

                if ($row['db_bank'] !== null &&
                    $row['db_bank'] === $newBank &&
                    $row['db_branch'] === $newBranch) {

                    if ($row['payable'] >= 100) {
                        $row['status'] = 'READY';
                    } else {
                        $row['status'] = 'CARRY_FORWARD';
                    }

                } else {
                    $row['status'] = 'BANK_MISMATCH';
                }
            }
        }

        unset($row);

        header("Location: view.php");
        exit;
    }
}

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

/* ===============================
   SEARCH FILTER
================================= */
if ($search !== '') {
    $results = array_filter($results, function($row) use ($search) {
        $search = strtolower($search);
        return strpos(strtolower($row['department_full']), $search) !== false
            || strpos(strtolower($row['bank']), $search) !== false
            || strpos(strtolower($row['type']), $search) !== false;
    });
}

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

/* ===============================
   SORTING
================================= */
if ($sortColumn !== '') {
    usort($results, function($a, $b) use ($sortColumn, $sortDir) {

        $valueA = $a[$sortColumn] ?? '';
        $valueB = $b[$sortColumn] ?? '';

        if (is_numeric($valueA) && is_numeric($valueB)) {
            $result = $valueA <=> $valueB;
        } else {
            $result = strcmp($valueA, $valueB);
        }

        return $sortDir === 'asc' ? $result : -$result;
    });
}

/* ===============================
   CALCULATE TOTALS (FILTERED DATA)
================================= */
$totalMonth = 0;
$totalCarry = 0;
$totalPayable = 0;

foreach ($results as $row) {
    $totalMonth += (float)$row['month_total'];
    $totalCarry += (float)$row['carry_in'];
    $totalPayable += (float)$row['payable'];
}

/* ===============================
   PAGINATION
================================= */
$totalRows = count($results);
$totalPages = max(1, ceil($totalRows / $perPage));
$offset = ($page - 1) * $perPage;
$results = array_slice($results, $offset, $perPage);

/* ===============================
   EXPORT BLOCK CHECK
================================= */
$hasMismatch = false;
foreach ($_SESSION['settlement_preview'] as $row) {
    if ($row['status'] === 'BANK_MISMATCH') {
        $hasMismatch = true;
        break;
    }
}
?>

<div class="container">
    <div class="page-header">
        <h2>Settlement Preview</h2>
        <?php if ($fileName): ?>
            <p class="page-subtitle">File: <?= htmlspecialchars($fileName) ?></p>
        <?php endif; ?>
    </div>

    <form method="get" style="margin-bottom:15px;">
        <input type="text" name="search" placeholder="Search Dept / Bank / Type"
               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>

    <form method="post">
    <div class="table-wrap">
        <table>
            <thead>
            <tr>
                <th>Department</th>
                <th>CSV Bank</th>
                <th>DB Bank</th>
                <th>CSV Branch</th>
                <th>DB Branch</th>
                <th>Account Type</th>
                <th>Landlord Amount</th>
                <th>Carry In</th>
                <th>Payable</th>
                <th>Status</th>
                <th>Action</th>
            </tr>
            </thead>

            <tbody>
            <?php foreach ($results as $row): ?>
                <?php
                $rowClass = '';
                if ($row['status'] === 'READY') $rowClass = 'row-ready';
                elseif ($row['status'] === 'CARRY_FORWARD') $rowClass = 'row-carry';
                elseif ($row['status'] === 'HOLD') $rowClass = 'row-hold';
                elseif ($row['status'] === 'BANK_MISMATCH') $rowClass = 'row-mismatch';
                ?>
                <tr class="<?= $rowClass ?>">
                    <td><?= htmlspecialchars($row['department_full']) ?></td>
                    <td><?= htmlspecialchars($row['bank']) ?></td>
                    <td><?= htmlspecialchars($row['db_bank'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($row['branch']) ?></td>
                    <td><?= htmlspecialchars($row['db_branch'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($row['type']) ?></td>
                    <td><strong><?= number_format((float)$row['month_total'], 2) ?></strong></td>
                    <td><?= number_format((float)$row['carry_in'], 2) ?></td>
                    <td><strong><?= number_format((float)$row['payable'], 2) ?></strong></td>
                    <td><?= htmlspecialchars($row['status']) ?></td>
                    <td>-</td>
                </tr>
            <?php endforeach; ?>

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

            </tbody>
        </table>
    </div>
    </form>

    <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>

    <br>
    
<form method="POST" style="margin-top:20px;">
    <input type="hidden" name="save_settlement" value="1">
    <button type="submit" class="btn btn-success">
        💾 Save Settlement Report
    </button>
    
</form>
    <?php if ($hasMismatch): ?>
        <div style="color:red;font-weight:bold;">
            Export blocked: Fix BANK_MISMATCH records first.
        </div>
    <?php else: ?>
        <a class="btn primary" href="history.php">
    Go to History to Process
</a>

<a class="btn" href="export_payment.php">
    Download READY Payments
</a>
    <?php endif; ?>

</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'; ?>