<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../../includes/db.php';

try {

    $loc_id  = $_GET['loc_id'] ?? null;
$account = $_GET['account'] ?? null;

if (!$loc_id || !$account) {
    //exit; // stop silently (prevents warnings + bad queries)
}

    $last_id   = isset($_GET['last_id']) ? (int)$_GET['last_id'] : 0;
    $last_date = $_GET['last_date'] ?? null;
    $last_balance = isset($_GET['last_balance']) ? (float)$_GET['last_balance'] : 0;

    $limit = 50;

    // =========================
    // START BALANCE
    // =========================
    if ($last_id == 0) {

        $stmt = $pdo->prepare("
            SELECT COALESCE(SUM(t_debit - t_credit),0)
            FROM transactions
            WHERE t_cr = :account
            AND co_id = :loc_id
        ");
        $stmt->execute([
            ':account' => $account,
            ':loc_id' => $loc_id
        ]);

        $running_balance = (float)$stmt->fetchColumn();

    } else {
        $running_balance = $last_balance;
    }

    // =========================
    // CURSOR CONDITION
    // =========================
    $cursor_sql = "";

    if ($last_id != 0 && $last_date) {
        $cursor_sql = "AND (
            t_date > :last_date OR
            (t_date = :last_date AND t_id > :last_id)
        )";
    }

    // =========================
    // MAIN QUERY
    // =========================
    $sql = "
        SELECT *
        FROM transactions
        WHERE t_cr = :account
        AND co_id = :loc_id
        $cursor_sql
        ORDER BY t_date ASC, t_id ASC
        LIMIT $limit
    ";

    $stmt = $pdo->prepare($sql);

    $params = [
        ':account' => $account,
        ':loc_id' => $loc_id
    ];

    if ($last_id != 0 && $last_date) {
        $params[':last_date'] = $last_date;
        $params[':last_id']   = $last_id;
    }

    $stmt->execute($params);

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$rows) exit;

    foreach ($rows as $row) {

        $running_balance += ($row['t_debit'] - $row['t_credit']);

        echo "<tr data-id='{$row['t_id']}' data-date='{$row['t_date']}'>
            <td>{$row['t_date']}</td>
            <td>{$row['t_cr']}</td>
            <td>{$row['t_type']}</td>
            <td>{$row['t_debit']}</td>
            <td>{$row['t_credit']}</td>
            <td>{$running_balance}</td>
        </tr>";
    }

} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage();
}