<?php
$file = 'index.php';
$content = file_get_contents($file);

if ($content === false) {
    die("Failed to read index.php");
}

$search = <<<'EOD'
    case 'accounting':
        $data['journal_entries'] = db()->query("SELECT je.*, 
                                                (SELECT SUM(debit) FROM acc_ledger WHERE journal_entry_id = je.id) as total_debit 
                                                FROM acc_journal_entries je 
                                                ORDER BY je.entry_date DESC, je.id DESC LIMIT 100")->fetchAll();
EOD;

$replace = <<<'EOD'
    case 'accounting':
        // Pagination for Journal Entries
        $currentPage = isset($_GET['p']) ? max(1, (int)$_GET['p']) : 1;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
        $offset = ($currentPage - 1) * $limit;

        $total_entries = db()->query("SELECT COUNT(*) FROM acc_journal_entries")->fetchColumn();
        $data['total_pages'] = ceil($total_entries / $limit);
        $data['current_page'] = $currentPage;

        $data['journal_entries'] = db()->query("SELECT je.*, 
                                                (SELECT SUM(debit) FROM acc_ledger WHERE journal_entry_id = je.id) as total_debit 
                                                FROM acc_journal_entries je 
                                                ORDER BY je.entry_date DESC, je.id DESC LIMIT $limit OFFSET $offset")->fetchAll();
EOD;

// Normalize line endings
$content = str_replace("\r\n", "\n", $content);
$search = str_replace("\r\n", "\n", $search);
$replace = str_replace("\r\n", "\n", $replace);

if (strpos($content, $search) !== false) {
    $newContent = str_replace($search, $replace, $content);
    file_put_contents($file, $newContent);
    echo "Successfully patched index.php\n";
} else {
    echo "Could not find the code block to replace.\n";
    // Debug: print a small chunk around where we expect it
    $pos = strpos($content, "case 'accounting':");
    if ($pos !== false) {
        echo "Found case 'accounting': at position $pos. Content around it:\n";
        echo substr($content, $pos, 500) . "\n";
    }
}