<?php
/**
 * SMART WA REMINDER (OTAK KURIR)
 * Dipanggil oleh cron_registry.php (slug: wa_reminder) setiap jam 09:00
 */
if (php_sapi_name() !== 'cli') die('Access denied.');

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$db = db();
$today = date('Y-m-d');
$h3 = date('Y-m-d', strtotime('+3 days'));
$h1 = date('Y-m-d', strtotime('+1 day'));

// ============================================================================
// 1. FUNGSI AMBIL TEMPLATE DARI DATABASE (Berdasarkan Slug)
// ============================================================================
function getTemplateFromDB($db, $slug) {
    try {
        $stmt = $db->prepare("SELECT message FROM wa_templates WHERE slug = ? LIMIT 1");
        $stmt->execute([$slug]);
        $msg = $stmt->fetchColumn();
        if ($msg) return $msg;
    } catch (\Throwable $e) {}
    
    // Fallback jika tabel belum ada atau slug belum dibuat di templates.php
    $defaults = [
        'reminder_h3'  => "Halo [nama], Tagihan akan jatuh tempo dalam 3 hari.",
        'reminder_h1'  => "Halo [nama], Tagihan akan jatuh tempo BESOK.",
        'reminder_due' => "Halo [nama], JATUH TEMPO HARI INI."
    ];
    return $defaults[$slug] ?? "Tagihan Anda sudah jatuh tempo.";
}

// ============================================================================
// 2. FUNGSI KIRIM WHATSAPP (WABLAS API)
// ============================================================================
function sendWablasCron($phone, $message, $db) {
    try {
        // Ambil config Wablas (Bisa disesuaikan jika config per cabang)
        $stmt = $db->query("SELECT setting_value FROM wa_config WHERE setting_key = 'wablas_token' LIMIT 1");
        $token = $stmt->fetchColumn();
        
        $stmt = $db->query("SELECT setting_value FROM wa_config WHERE setting_key = 'wablas_base_url' LIMIT 1");
        $baseUrl = rtrim($stmt->fetchColumn() ?: '', '/');

        if (!$token || !$baseUrl) {
            echo "  [SKIP] Wablas belum dikonfigurasi di database.\n";
            return false;
        }

        $url = $baseUrl . '/send-message?' . http_build_query([
            'phone' => $phone, 
            'message' => $message, 
            'token' => $token
        ]);
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0
        ]);
        curl_exec($curl);
        curl_close($curl);
        return true;
    } catch (\Throwable $e) {
        return false;
    }
}

// ============================================================================
// 3. LOGIKA UTAMA: CARI PELANGGAN & KIRIM PESAN
// ============================================================================
function processReminders($db, $date, $slug, $label) {
    $template = getTemplateFromDB($db, $slug);
    $count = 0;
    
    // Query gabung ke tabel packages agar bisa memanggil [paket]
    $sql = "SELECT b.due_date, b.amount, c.name, c.phone, c.customer_number, p.name as package_name
            FROM bills b
            JOIN customers c ON b.customer_id = c.id
            LEFT JOIN packages p ON c.package_id = p.id
            WHERE b.due_date = ? AND b.status = 'unpaid' AND c.phone IS NOT NULL AND c.phone != ''";
            
    $stmt = $db->prepare($sql);
    $stmt->execute([$date]);
    
    foreach ($stmt->fetchAll() as $row) {
        // Format Nomor HP (0812... -> 62812...)
        $phone = preg_replace('/[^0-9]/', '', $row['phone']);
        if (substr($phone, 0, 1) === '0') $phone = '62' . substr($phone, 1);
        elseif (substr($phone, 0, 2) !== '62') $phone = '62' . $phone;
        
        // ⚠️ GANTI URL DI BAWAH INI DENGAN DOMAIN ASLI ANDA!
        $linkBayar = "https://domain-anda.com/public/pay.php?id=" . urlencode($row['customer_number']); 
        
        // Ganti Placeholder [xxx] dengan data asli dari database
        $msg = str_replace(
            ['[customer_number]', '[nama]', '[paket]', '[Link Pembayaran]', '{name}', '{date}', '{amount}'],
            [
                $row['customer_number'] ?? '-', 
                $row['name'], 
                $row['package_name'] ?? 'Internet', 
                $linkBayar,
                $row['name'],
                date('d/m/Y', strtotime($row['due_date'])),
                number_format($row['amount'], 0, ',', '.')
            ],
            $template
        );
        
        // Kirim WA (Uncomment baris di bawah jika Wablas siap dipakai)
        // sendWablasCron($phone, $msg, $db); 
        
        echo "  [{$label}] -> {$row['name']} ({$phone})\n";
        $count++;
    }
    return $count;
}

// ============================================================================
// 4. EKSEKUSI
// ============================================================================
echo "=== CRON REMINDER START: " . date('Y-m-d H:i:s') . " ===\n";

$c1 = processReminders($db, $h3, 'reminder_h3', 'H-3');
$c2 = processReminders($db, $h1, 'reminder_h1', 'H-1');
$c3 = processReminders($db, $today, 'reminder_due', 'HARI H');

echo "=== SELESAI: H-3 ($c1 pesan), H-1 ($c2 pesan), Hari H ($c3 pesan) ===\n";