<?php
require_once __DIR__.'/../inc/config.php'; 
require_once __DIR__.'/../inc/db.php'; 
require_once __DIR__.'/../inc/http.php';
require_once __DIR__.'/../inc/helpers.php';

// Ambil semua templat dari tetapan
$templates_raw = setting('ABANDONED_CART_TEMPLATES', "Assalamualaikum {nama}, pesanan #{id_pesanan} bernilai {jumlah} belum diselesaikan. Klik untuk sambung bayaran: {pautan_bayaran}");

// Pecahkan kepada array, buang baris kosong
$templates = array_filter(array_map('trim', explode("\n", $templates_raw)));

if (empty($templates)) {
    exit("Tiada templat mesej pesanan terbengkalai ditetapkan.");
}

// Cari pesanan yang terbengkalai selepas 20 minit
$st = db()->query("SELECT * FROM orders WHERE status='Pending' AND recovery_sent=0 AND datetime(created_at,'+20 minutes') <= datetime('now') LIMIT 10");
$list = $st->fetchAll();

foreach($list as $o) {
    // Pilih satu templat secara rawak
    $chosen_template = $templates[array_rand($templates)];

    // Bina pautan bayaran yang betul
    $payment_link = '';
    if ($o['payment_method'] === 'ToyyibPay' && !empty($o['bill_code'])) {
    $payment_link = 'https://toyyibpay.com/' . $o['bill_code'];
} else {
    // Guna pautan ke halaman LENGKAPKAN BAYARAN yang baru
    $base_url = rtrim(setting('TOYYIBPAY_RETURN_URL', 'https://vanillablue.mymukmin.com/thank_you.php'), '/');
    $payment_link = str_replace('thank_you.php', '', $base_url) . 'lengkapkan_bayaran.php?order=' . $o['id'];
}

    // Gantikan pembolehubah dalam templat
    $message_to_send = str_replace(
        ['{nama}', '{id_pesanan}', '{jumlah}', '{pautan_bayaran}'],
        [$o['name'], $o['id'], money($o['amount']), $payment_link],
        $chosen_template
    );

    send_whatsapp($o['phone'], $message_to_send);

    $up = db()->prepare("UPDATE orders SET recovery_sent=1 WHERE id=?"); 
    $up->execute([$o['id']]);
}

echo "Proses pemulihan selesai. " . count($list) . " mesej dihantar.";