<?php

namespace App\Livewire\Products;

use App\Models\Category;
use App\Models\Product;
use App\Models\Unit;
use Livewire\Component;
use Livewire\WithFileUploads;

class ProductForm extends Component
{
    use WithFileUploads;

    public ?Product $product = null;
    public bool $editMode = false;

    // Form fields
    public string $name = '';
    public string $name_ar = '';
    public ?int $category_id = null;
    public string $sku = '';
    public string $barcode = '';
    public string $description = '';
    public string $description_ar = '';
    public float $cost_price = 0;
    public float $selling_price = 0;
    public ?string $expiry_date = null;
    public ?int $unit_id = null;
    public string $volume = '';
    public bool $is_repair_part = false;
    public $is_service = 0; // Changed from bool to allow int (0/1) binding
    public bool $track_inventory = true;
    public int $min_stock_level = 0;
    public bool $is_active = true;
    public $image;

    protected function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'name_ar' => 'nullable|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'description_ar' => 'nullable|string',
            'cost_price' => 'required|numeric|min:0',
            'selling_price' => 'required|numeric|min:0',
            'expiry_date' => 'nullable|date',
            'unit_id' => 'nullable|exists:units,id',
            'volume' => 'nullable|string|max:100',
            'is_repair_part' => 'boolean',
            'is_service' => 'boolean',
            'track_inventory' => 'boolean',
            'min_stock_level' => 'required|integer|min:0',
            'is_active' => 'boolean',
            'image' => 'nullable|image|max:2048',
        ];
    }

    public function mount(?int $id = null)
    {
        if ($id) {
            $this->product = Product::findOrFail($id);
            $this->editMode = true;
            $this->fillFromProduct();
        } else {
            $this->sku = Product::generateSku();
        }
    }

    protected function fillFromProduct()
    {
        $this->name = $this->product->name ?? '';
        $this->name_ar = $this->product->name_ar ?? '';
        $this->category_id = $this->product->category_id;
        $this->sku = $this->product->sku ?? '';
        $this->barcode = $this->product->barcode ?? '';
        $this->description = $this->product->description ?? '';
        $this->description_ar = $this->product->description_ar ?? '';
        $this->cost_price = $this->product->cost_price ?? 0;
        $this->selling_price = $this->product->selling_price ?? 0;
        $this->expiry_date = $this->product->expiry_date;
        $this->unit_id = $this->product->unit_id;
        $this->volume = $this->product->volume ?? '';
        $this->is_repair_part = $this->product->is_repair_part ?? false;
        // Cast to integer for select binding compatibility
        $this->is_service = $this->product->is_service ? 1 : 0;
        
        // STRICT LOGIC: Force track_inventory based on is_service
        $this->track_inventory = !$this->is_service;
        
        $this->min_stock_level = $this->product->min_stock_level ?? 0;
        $this->is_active = $this->product->is_active ?? true;
    }

    public function updatedIsService($value)
    {
        // Ensure we treat "0", 0, false as Physical (false)
        // Ensure "1", 1, true as Service (true)
        $isService = (bool) $value;
        
        // Strict Logic
        $this->track_inventory = !$isService;
    }

    public function generateSku()
    {
        $this->sku = Product::generateSku();
    }

    public function generateBarcode()
    {
        $this->barcode = Product::generateBarcode();
    }

    public function save()
    {
        $validated = $this->validate();

        // Handle image upload
        if ($this->image) {
            $validated['image'] = $this->image->store('products', 'public');
        }

        if ($this->editMode) {
            $this->product->update($validated);
            session()->flash('success', __('Product updated successfully.'));
        } else {
            Product::create($validated);
            session()->flash('success', __('Product created successfully.'));
        }

        return redirect()->route('products.index');
    }

    public function render()
    {
        $categories = Category::active()->orderBy('sort_order')->get();
        $units = Unit::active()->orderBy('name')->get();

        return view('livewire.products.form', [
            'categories' => $categories,
            'units' => $units,
        ]);
    }
}
