<?php

namespace App\Livewire\Shipment;

use App\Livewire\Forms\ShipmentForm;
use App\Livewire\Forms\TrackingForm;
use App\Mail\Admin\ShipmentCreated;
use App\Models\Shipment;
use App\Utils\ShipmentFaker;
use Illuminate\Support\Facades\Mail;
use Livewire\Component;
use Livewire\WithFileUploads;

class Create extends Component
{

    use WithFileUploads;
    use ShipmentFaker;

    public ShipmentForm $shipment_form; 
    public TrackingForm $tracking_form;

    public function mount() {
        $this->shipment_form->tracking_code = tracking_code();
        $this->fillForm();
    }

    public function rules() {
        return [
            'shipment_form.photo' => $this->shipment_form->photo!=null ? 'required|image|max:3072': '',
        ];
    }

    public function validationAttributes() {
        return [
            'shipment_form.photo' => 'photo',
        ];
    }

    public function create() {
        $this->validate();
        $this->shipment_form->photo = $this->shipment_form->photo!=null ? '/storage/'.$this->shipment_form->photo->store('shipment_photos', 'public') : null;
        
        $shipment = Shipment::create($this->shipment_form->all());
        $shipment->tracking()->create($this->tracking_form->all());

        session()->flash('success', 'Shipment created successfully.');
        Mail::to($shipment->receiver_email)->send(new ShipmentCreated($shipment));
        $this->redirect(route('shipment.single', $shipment->tracking_code), true);
    }
}
