<?php
date_default_timezone_set('Asia/Jakarta');
// cron_auto_suspend.php
// Crontab: 0 1 * * * /usr/bin/php /path/to/cron_auto_suspend.php

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/MikroTik.php';
// require_once __DIR__ . '/../classes/WhatsApp.php';

if (php_sapi_name() !== 'cli' && empty($GLOBALS['CRON_MANAGER_EXEC'])) die('Access denied.');

$db = db();
$mt = new MikroTik();

$stmt = $db->query("
    SELECT c.id, c.name, c.phone, c.pppoe_username 
    FROM customers c
    JOIN bills b ON c.id = b.customer_id
    WHERE b.status = 'overdue' AND c.status = 'active'
    GROUP BY c.id
");

$count = 0;
foreach ($stmt->fetchAll() as $c) {
    try {
        // 1. disable secret/user & Kick dari MikroTik
        $mt->suspendCustomer($c['pppoe_username']);
        
        // 2. Update customer → suspended
        Customer::update($c['id'], ['status' => 'suspended']);
        
        // 3. Kirim notifikasi WhatsApp
        // WhatsApp::send($c['phone'], "Halo {$c['name']}, layanan Anda di-suspend karena tagihan overdue.");
        
        $count++;
    } catch (\Throwable $e) {
        echo "Error suspending {$c['name']}: " . $e->getMessage() . "\n";
    }
}
echo "Auto-suspended $count customers.\n";