<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TransaksiBuket;
use App\Services\WhatsAppService; // Import Service
use Illuminate\Http\Request;

class PesananBuketController extends Controller
{
    public function index()
    {
        $pesanan = TransaksiBuket::whereIn('status_transaksi', ['menunggu_verifikasi', 'diterima'])
            ->orderBy('created_at', 'ASC')
            ->get();
        return view('admin.pesanan.buket', compact('pesanan'));
    }

    public function updateStatus(Request $request, $id)
    {
        try {
            $pesanan = TransaksiBuket::with(['pelanggan', 'buket'])->findOrFail($id);
            $status = $request->jenis === 'terima' ? 'diterima' : ($request->jenis === 'selesai' ? 'selesai' : 'ditolak');
            $labels = [
                'diterima' => 'telah diterima',
                'selesai'  => 'berhasil diselesaikan',
                'ditolak'  => 'telah ditolak'
            ];
            $sessionKey = $status === 'ditolak' ? 'error' : 'success';
            $sessionMsg = "Pesanan {$pesanan->no_invoice} " . $labels[$status] . "!";
            session()->flash($sessionKey, $sessionMsg);
            $pesanan->update(['status_transaksi' => $status]);
            $waUrl = WhatsAppService::getBuketNotification($pesanan, $status);
            return response()->json([
                'success' => true,
                'wa_url' => $waUrl
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}
