<?php

namespace App\Http\Livewire\Pages\Admin;

use App\Models\Cars;
use App\Models\Category;
use App\Models\Make;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Log;

class Upload extends Component
{
    use WithFileUploads;

    // Car model fields
    public $title;
    public $audit_price;
    public $old_price;
    public $price;
    public $features;
    public $is_sold = 0;
    public $is_in_order = 0;
    public $images = []; // To handle multiple images
    public $make_id;
    public $category_id;

    // CarDetails model fields
    public $mileage;
    public $first_registration;
    public $power;
    public $transmission;
    public $fuel;
    public $drive_type;
    public $consumption;
    public $co2_emissions;
    public $location;

    // CarGenerals model fields
    public $vehicle_id;
    public $model;
    public $body_color;
    public $type_of_finish;
    public $interior_color;
    public $interior_material;
    public $body;
    public $doors;
    public $seats;

    // CarEngine model fields
    public $engine_capacity;
    public $speeds;
    public $emission_class;

    public $categories; // This will hold the list of categories
    public $makes; // This will hold the list of makes

    public $isEditing;
    public $editListingId;

    public function mount($id = null)
    {
        $this->categories = Category::all();
        $this->makes = Make::all();

        // If an ID is provided, fetch the car and its associated models for editing
        if ($id) {
            $this->isEditing = true;
            $car = Cars::with('car_detail', 'car_general', 'car_engine')->findOrFail($id);

            // Populate fields for editing
            $this->editListingId = $car->id;
            $this->title = $car->title;
            $this->audit_price = $car->audit_price;
            $this->old_price = $car->old_price;
            $this->price = $car->price;
            $this->features = $car->features;
            $this->is_sold = $car->is_sold;
            $this->is_in_order = $car->is_in_order;
            $this->images = $car->images;
            $this->make_id = $car->make_id;
            $this->category_id = $car->category_id;

            // Fill CarDetails, CarGeneral, and CarEngine
            $this->mileage = $car->car_detail->mileage ?? '';
            $this->first_registration = $car->car_detail->first_registration ?? '';
            $this->power = $car->car_detail->power ?? '';
            $this->transmission = $car->car_detail->transmission ?? '';
            $this->fuel = $car->car_detail->fuel ?? '';
            $this->drive_type = $car->car_detail->drive_type ?? '';
            $this->consumption = $car->car_detail->consumption ?? '';
            $this->co2_emissions = $car->car_detail->co2_emissions ?? '';
            $this->location = $car->car_detail->location ?? '';

            $this->vehicle_id = $car->car_general->vehicle_id ?? '';
            $this->model = $car->car_general->model ?? '';
            $this->body_color = $car->car_general->body_color ?? '';
            $this->type_of_finish = $car->car_general->type_of_finish ?? '';
            $this->interior_color = $car->car_general->interior_color ?? '';
            $this->interior_material = $car->car_general->interior_material ?? '';
            $this->body = $car->car_general->body ?? '';
            $this->doors = $car->car_general->doors ?? '';
            $this->seats = $car->car_general->seats ?? '';

            $this->engine_capacity = $car->car_engine->engine_capacity ?? '';
            $this->speeds = $car->car_engine->speeds ?? '';
            $this->emission_class = $car->car_engine->emission_class ?? '';
        }
    }

    public function rules()
    {
        return [
            'title' => ['string', 'required', 'min:4'],
            'audit_price' => ['required', 'numeric'],
            'old_price' => ['required', 'numeric'],
            'price' => ['required', 'numeric'],
            'features' => ['required', 'string'],
            'is_sold' => ['required', 'numeric'],
            'is_in_order' => ['required', 'numeric'],
            'make_id' => ['required', 'exists:makes,id'],
            'category_id' => ['required', 'exists:categories,id'],
            'mileage' => ['required', 'string'],
            'first_registration' => ['required', 'string'],
            'power' => ['required', 'string'],
            'transmission' => ['required', 'string'],
            'fuel' => ['required', 'string'],
            'drive_type' => ['required', 'string'],
            'consumption' => ['required', 'string'],
            'co2_emissions' => ['required', 'string'],
            'location' => ['required', 'string'],
            'vehicle_id' => ['required', 'string'],
            'model' => ['required', 'string'],
            'body_color' => ['required', 'string'],
            'type_of_finish' => ['required', 'string'],
            'interior_color' => ['required', 'string'],
            'interior_material' => ['required', 'string'],
            'body' => ['required', 'string'],
            'doors' => ['required', 'string'],
            'seats' => ['required', 'string'],
            'engine_capacity' => ['required', 'string'],
            'speeds' => ['required', 'string'],
            'emission_class' => ['required', 'string'],
            // 'images' => ['required', 'array'], // Ensuring images are provided
            'images.*' => 'image|mimes:jpeg,png,jpg,gif|min:1|max:8048', // Validating each image
        ];
    }

    public function updated($property)
    {
        $this->validateOnly($property);
    }

    public function removeImage($index)
    {
        unset($this->images[$index]);
    }

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

        // Convert the comma-separated string into an array
        $featuresArray = explode(',', $this->features);

        // Trim the elements in case there are extra spaces
        $featuresArray = array_map('trim', $featuresArray);

        // Start transaction for creating or updating
        DB::beginTransaction();

        try {
            // Check if we are editing or creating
            if ($this->isEditing) {
                $car = Cars::findOrFail($this->editListingId);
            } else {
                $car = new Cars();
            }

            // Handle image uploads
            $imagePaths = [];
            if ($this->images) {
                foreach ($this->images as $image) {
                    // Store each image in the public folder
                    $imageName = time() . uniqid() . '.' . $image->getClientOriginalName();
                    $imagePath = $image->storeAs('uploads/', $imageName); // Store in 'public/uploads'
                    $imagePaths[] = $imagePath;
                }
            }

            // Save car information
            $car->title = $this->title;
            $car->audit_price = $this->audit_price;
            $car->old_price = $this->old_price;
            $car->price = $this->price;
            $car->features = json_encode($featuresArray);
            $car->is_sold = $this->is_sold;
            $car->is_in_order = $this->is_in_order;
            $car->make_id = $this->make_id;
            $car->category_id = $this->category_id;
            $car->images = $imagePaths; // Save image paths to the database

            $car->save();

            // Save related models (CarDetail, CarGeneral, CarEngine)
            $car->car_detail()->updateOrCreate(
                ['car_id' => $car->id],
                [
                    'mileage' => $this->mileage,
                    'first_registration' => $this->first_registration,
                    'power' => $this->power,
                    'transmission' => $this->transmission,
                    'fuel' => $this->fuel,
                    'drive_type' => $this->drive_type,
                    'consumption' => $this->consumption,
                    'co2_emissions' => $this->co2_emissions,
                    'location' => $this->location,
                ]
            );

            $car->car_general()->updateOrCreate(
                ['car_id' => $car->id],
                [
                    'vehicle_id' => $this->vehicle_id,
                    'make_id' => $this->make_id,
                    'model' => $this->model,
                    'body_color' => $this->body_color,
                    'type_of_finish' => $this->type_of_finish,
                    'interior_color' => $this->interior_color,
                    'interior_material' => $this->interior_material,
                    'body' => $this->body,
                    'doors' => $this->doors,
                    'seats' => $this->seats,
                ]
            );

            $car->car_engine()->updateOrCreate(
                ['car_id' => $car->id],
                [
                    'engine_capacity' => $this->engine_capacity,
                    'consumption' => $this->consumption,
                    'speeds' => $this->speeds,
                    'co2_emissions' => $this->co2_emissions,
                    'emission_class' => $this->emission_class,
                ]
            );

            // Increment the number_of_cars for the category and make
            $category = Category::find($this->category_id);
            if ($category) {
                $category->increment('number_of_cars');
            }

            $make = Make::find($this->make_id);
            if ($make) {
                $make->increment('number_of_cars');
            }

            DB::commit(); // Commit transaction

            session()->flash('message', $this->isEditing ? 'Car updated successfully.' : 'Car added successfully!');
        } catch (\Exception $e) {
            DB::rollBack(); // Rollback transaction on error
            Log::error("Error storing car: " . $e->getMessage());
            session()->flash('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.pages.admin.upload')->layout('layouts.admin');
    }
}
