<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::orderBy('id', 'desc')->get();
        return view('admin.order.index', compact('orders'));
    }

    public function store(Request $request)
    {
        $data = $request->all();
        Order::create($data);
        return redirect('/admin/order');
    }

    public function update(Request $request, $id)
    {
        $order = DB::table('orders')->where('id', $id);
        $order->update([
            'status' => $request->status,
            'shipping_resi' => $request->shipping_resi
        ]);
        //send notification to user
        if ($request->status == 'on_delivery') {
            $this->sendNotificationToUser($order->first()->user_id, 'Paket Dikirim Dengan Nomor Resi ' . $request->shipping_resi);
        }
        return redirect('/admin/order');
    }

    public function destroy($id)
    {
        Order::findOrFail($id)->delete();
        return  redirect('/admin/order');
    }


    public function sendNotificationToUser($userId, $message)
    {
        // Dapatkan FCM token user dari tabel 'users'
        $user = User::find($userId);
        $token = $user->fcm_id;
        // Kirim notifikasi ke perangkat Android
        $messaging = app('firebase.messaging');
        $notification = Notification::create('Paket Dikirim, Nantikan Promo Diskon Menarik lainnya', $message);

        $message = CloudMessage::withTarget('token', $token)
            ->withNotification($notification)
            ->withData(['message' => $message]);

        $messaging->send($message);
    }

    
}
