<?php

namespace App\Livewire\Tracking;

use Livewire\Component;
use App\Models\Tracking;
use Livewire\Attributes\Validate;
use App\Mail\Admin\ShipmentCreated;
use App\Livewire\Forms\TrackingForm;
use App\Mail\Admin\TrackingUpdated;
use Illuminate\Support\Facades\Mail;

class Edit extends Component
{
    public TrackingForm $tracking_form;
    public Tracking $tracking;

    #[Validate('required|min:0|max:5')]
    public $status_code;
    public $hold_reason = null;

    public function render() {
        return view('livewire.tracking.edit');
    }

    public function rules() {
        return [
            'hold_reason' => $this->status_code==0 ? 'required': '',
        ];
    }

    public function mount() {
        $this->status_code = $this->tracking->status_code;
        $this->hold_reason = $this->tracking->hold_reason;
        $this->tracking_form->setTrackingForm($this->tracking);
    }

    public function edit() {
        $this->validate();

        $extras = [
            'status_code' => $this->status_code,
            'hold_reason' => $this->hold_reason,
        ];
        $details = array_merge($extras, $this->tracking_form->all());
        $this->tracking->update($details);

        session()->flash('success', 'Tracking updated successfully.');

        Mail::to($this->tracking->shipment->receiver_email)->send(new TrackingUpdated($this->tracking));
        $this->redirect(route('tracking.single', $this->tracking->id), true);
    }
}
