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

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

$companyId = $_SESSION['company_id'];
$engine = new SettlementEngine($pdo, $companyId);

/* ===============================
   GET RUN ID
================================= */
$runId = (int)($_GET['run_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, $companyId]);
$run = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* ===============================
   PREVENT DOUBLE PROCESSING
================================= */
if ($run['status'] !== 'DRAFT') {
    die("⚠️ This settlement is already processed.");
}

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

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

/* ===============================
   PROCESS EACH ROW
================================= */
foreach ($rows as $row) {

    if ($row['status'] === 'READY' || $row['status'] === 'CARRY_FORWARD') {

        $engine->process(
            $row['department_code'],
            $row['month_total'],
            true // ✅ THIS UPDATES CARRY FORWARD
        );
    }
}

/* ===============================
   UPDATE RUN STATUS
================================= */
$stmt = $pdo->prepare("
    UPDATE settlement_runs
    SET status = 'PROCESSED'
    WHERE id = ?
");

$stmt->execute([$runId]);

/* ===============================
   REDIRECT
================================= */
header("Location: history.php?processed=1");
exit;