<?php
require_once __DIR__ . '/db_config.php';

try {

    // Tables to maintain
    $tables = [
        'tblsales_partition',
        'tblsalesitemdetails_partition'
    ];

    // Create partitions for next N months
    $months_ahead = 6;

    date_default_timezone_set('Asia/Kolkata');

    for ($i = 0; $i <= $months_ahead; $i++) {

        $future = strtotime("+$i month");

        $year  = (int)date('Y', $future);
        $month = (int)date('m', $future);

        foreach ($tables as $table) {

            $sql = "SELECT public.create_monthly_partition($1, $2, $3)";
            $stmtName = "create_part_" . $table . "_" . $year . "_" . $month;

            pg_prepare($con, $stmtName, $sql);
            $result = pg_execute($con, $stmtName, [$table, $year, $month]);

            if (!$result) {
                echo "❌ Failed: $table $year-$month → " . pg_last_error($con) . "\n";
            } else {
                echo "✅ Checked/Created: $table $year-$month\n";
            }
        }
    }

    mch_db_release($con);

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