<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\OrderModel;

class Notification extends BaseController
{
    /**
     * Mengirim notifikasi pembayaran atau status pesanan via email, WA, dan sistem notifikasi internal
     */
    public function send($id_order)
    {
        $db = \Config\Database::connect();
        $orderModel = new OrderModel();
        $order = $orderModel->find($id_order);

        if (!$order) {
            return redirect()->back()->with('error', 'Pesanan tidak ditemukan.');
        }

        // Ambil data detail profil customer
        $customer = $db->table('customers')->where('id_customer', $order['id_customer'])->get()->getRow();
        if (!$customer) {
            return redirect()->back()->with('error', 'Data kontak customer tidak lengkap.');
        }

        $pesan = "Halo {$customer->nama_customer}, pesanan Anda dengan nomor {$order['nomor_order']} saat ini berstatus: " . strtoupper($order['status_order']) . ". Terima kasih.";

        // 1. Simpan salinan log ke sistem notifikasi internal (tabel notifications)
        $db->table('notifications')->insert([
            'id_user'    => session()->get('id_user') ?? 1,
            'title'      => "Status Update: {$order['nomor_order']}",
            'message'    => $pesan,
            'is_read'    => false,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        // 2. Mocking Email Delivery (Menggunakan mailer default)
        // \Config\Services::email()->setTo($customer->email)->setMessage($pesan)->send();

        // 3. Mocking Whatsapp API Delivery (Menggunakan WhatsApp API Key sistem settings)
        $systemSetting = $db->table('system_settings')->first();
        $waApiKey = $systemSetting ? $systemSetting['wa_api_key'] : '';

        // Jika API Key diatur, maka pengiriman bisa diteruskan ke Gateway pihak ketiga
        // curl_post("https://api.wa-gateway.com", ['key' => $waApiKey, 'target' => $customer->telepon, 'message' => $pesan]);

        return redirect()->back()->with('success', 'Seluruh rangkaian notifikasi digital (Sistem, Email, WA) telah sukses dikirim.');
    }
}