<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Courier;
use App\Models\CourierUpdate;
use App\Mail\CourierUpdated;
use Illuminate\Support\Facades\Mail;

class CourierUpdateController extends Controller
{
    public function store(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|string|max:255',
            'location' => 'required|string|max:255',
            'comment' => 'nullable|string',
        ]);

        $courier = Courier::findOrFail($id);

       $update = CourierUpdate::create([
            'courier_id' => $courier->id,
            'status' => $request->status,
            'location' => $request->location,
            'comment' => $request->comment,
        ]);

        // Optionally update courier's current location and status
        $courier->update([
            'current_location' => $request->location,
            'status' => $request->status,
        ]);

        Mail::to([$courier->receiver_email, $courier->sender_email])
    ->send(new CourierUpdated($courier, $update));

        // Mail::to($courier->receiver_email)->send(new CourierUpdated($courier, $update));

        return redirect()->back()->with('success', 'Tracking update added successfully.');
    }
}
