<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Invoice;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;

class NotificationController extends Controller {
    public function sendBlast(Request $request) {
        $token = 'V19K6PDjznybVh5LWoDS'; 
        $template = $request->message;
        $type = $request->type; // 'tagihan', 'pengurasan', atau 'selesai'
        $sentCount = 0;

        // Jika tipe tagihan, ambil Invoice yang UNPAID. Jika lain, ambil semua USER.
        $data = ($type == 'tagihan') 
            ? Invoice::with(['user.profile', 'meterReading'])->where('status', 'unpaid')->get()
            : User::with('profile')->get();

        foreach ($data as $item) {
            $user = ($type == 'tagihan') ? $item->user : $item;
            $rawPhone = $user->profile->phone_number ?? null;
            if (!$rawPhone) continue;

            $phone = str_starts_with($rawPhone, '0') ? '62' . substr($rawPhone, 1) : $rawPhone;

            // Logika ganti variabel [nama], [total], [bulan], [invoice]
            $search = ['[nama]', '[total]', '[bulan]', '[invoice]'];
            $replace = [
                $user->name,
                ($type == 'tagihan') ? number_format($item->total_amount, 0, ',', '.') : '',
                ($type == 'tagihan') ? Carbon::create($item->meterReading->year, $item->meterReading->month, 1)->translatedFormat('F Y') : '',
                ($type == 'tagihan') ? $item->invoice_number : ''
            ];
            $pesanFinal = str_replace($search, $replace, $template);

            $response = Http::withHeaders(['Authorization' => $token])->withoutVerifying()
                ->post('https://api.fonnte.com/send', ['target' => $phone, 'message' => $pesanFinal]);

            if ($response->successful()) {
                if ($type == 'tagihan') $item->update(['published_at' => now()]);
                $sentCount++;
            }
        }
        return response()->json(['status' => 'success', 'terkirim' => $sentCount]);
    }
}