<?php

namespace App\Http\Controllers\Dashboard\Admin;

use App\Helpers\AdminHelper;
use App\Mail\ShipmentNotification;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\ShipmentLocation;
use App\Http\Controllers\Controller;
use App\Models\Shipment;
use Illuminate\Support\Facades\Mail;

class ShipmentLocationController extends Controller
{
    public function store(Request $request, $uuid)
    {
        $data = $request->validate([
            'status' => 'required',
            'location' => 'required',
            'google_map_location' => 'required',
            'description' => 'nullable',
            'date' => 'required',
            'time' => 'required',
        ]);
        $shipment = Shipment::where('uuid', $uuid)->first();

        $data['uuid'] = Str::uuid();
        $data['shipment_id'] = $shipment->id;

        $shipment->status = $data['status'];
        $shipment->current_location = $data['location'];
        $shipment->update();

        ShipmentLocation::create($data);

        if ($request->notification == 'Email') {
            AdminHelper::mailConfig(auth('admin')->user()->id);

            try {
                Mail::to($shipment->client_email)->send(new ShipmentNotification($shipment, 'Parcel Status Notification' . now()));
                Mail::to($shipment->sender_email)->send(new ShipmentNotification($shipment, 'Parcel Status Notification' . now()));
            } catch (\Exception $e) {
                session()->flash('email_error', 'Error: ' . $e->getMessage());
            }
        }

        return redirect()->back()->with('success', 'Shipment location updated successfully!');
    }

    public function delete($uuid)
    {
        $location = ShipmentLocation::where('uuid', $uuid)->first();
        $location->delete();
        return redirect()->back()->with('success', 'Shipment location deleted successfully!');
    }
}
