<?php

// ===============================
// LOAD FILE .env LARAVEL
// ===============================
$envPath = '/home/nokosmurah/public_html/.env';

if (!file_exists($envPath)) {
    die(".env file tidak ditemukan" . PHP_EOL);
}

$env = parse_ini_file($envPath, false, INI_SCANNER_RAW);

if ($env === false) {
    die("Gagal membaca file .env" . PHP_EOL);
}

// ===============================
// AMBIL KONFIGURASI DATABASE
// ===============================
$host = $env['DB_HOST'] ?? '127.0.0.1';
$port = $env['DB_PORT'] ?? '3306';
$db   = $env['DB_DATABASE'] ?? '';
$user = $env['DB_USERNAME'] ?? '';
$pass = $env['DB_PASSWORD'] ?? '';

// ===============================
// VALIDASI
// ===============================
if (!$db || !$user) {
    die("Konfigurasi database tidak lengkap di .env" . PHP_EOL);
}

// ===============================
// KONEKSI DATABASE
// ===============================
try {
    $pdo = new PDO(
        "mysql:host={$host};port={$port};dbname={$db};charset=utf8mb4",
        $user,
        $pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );
} catch (PDOException $e) {
    die("Koneksi database gagal: " . $e->getMessage() . PHP_EOL);
}

// ===============================
// HITUNG RANGE BULAN LALU
// ===============================
$startLastMonth = date('Y-m-01 00:00:00', strtotime('first day of last month'));
$startThisMonth = date('Y-m-01 00:00:00');

// ===============================
// EKSEKUSI DELETE (BULAN LALU)
// ===============================
$sql = "
    DELETE FROM orders
    WHERE created_at >= :start_last_month
    AND created_at < :start_this_month
    AND status IN ('SUCCESS', 'FAILED', 'CANCELED')
";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':start_last_month' => $startLastMonth,
    ':start_this_month' => $startThisMonth
]);

// ===============================
// OUTPUT
// ===============================
echo "✅ Berhasil menghapus {$stmt->rowCount()} data orders (bulan lalu, non-pending)" . PHP_EOL;