<?php

namespace App\Controllers\Dcron;

use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Bday extends BaseController
{
    use ResponseTrait;

    protected $NasabahModel;
    
    public function __construct()
    {
        $this->NasabahModel = model('App\Models\Potensiwilayah\DatanasabahModel');
    }

    public function birthday()
    {
        try {
            // Ambil data nasabah yg closing = 1, yang berulang tahun hari ini 
            $nasabah = $this->NasabahModel->get_bday_now();
            
            $successCount = 0;
            $failCount = 0;
            $total = count($nasabah);

            // Penanganan khusus jika tidak ada pelanggan yang berulang tahun
            if ($total == 0) {
                log_message('info', 'No customers with birthday today. Process completed with no action.');
                return "No customers with birthday today. Process completed.";
            }

            // Log dimulainya proses
            log_message('info', 'Started. Found ' . $total . ' customers with birthday today.');

            foreach ($nasabah as $cus) {
                // Prepare pesan
                $pesan = 'Selamat Ulang Tahun '.$cus->nama_calon.'. Kami dari Pegadaian '.$cus->satker.' mendoakan kesehatan, kebahagiaan, dan kesuksesan untuk Anda.';
                
                // Kirim pesan WhatsApp menggunakan helper
                $response = send_wax($cus->no_wa, $pesan);
                
                // Log hasil pengiriman
                if (!empty($response)) {
                    $successCount++;
                    log_message('info', "Birthday message sent to {$cus->nama_calon} ({$cus->no_wa})");
                } else {
                    $failCount++;
                    log_message('error', "Failed to send birthday message to {$cus->nama_calon} ({$cus->no_wa})");
                }
                
                // Delay untuk menghindari rate limiting
                sleep(2);
            }

            // Log hasil akhir
            log_message('info', "Birthday process completed. Total: {$total}, Success: {$successCount}, Failed: {$failCount}");
            return "Birthday process completed. Total: {$total}, Success: {$successCount}, Failed: {$failCount}";

        } catch (\Exception $e) {
            log_message('error', "Birthday process error: " . $e->getMessage());
            return "Error: " . $e->getMessage();
        }
    }
}