<?php

namespace App\Livewire\WorkOrders;

use App\Models\Estimate;
use App\Models\WorkOrder;
use App\Models\WorkOrderTask;
use App\Models\User;
use Livewire\Component;

class Create extends Component
{
    public Estimate $estimate;
    public $work_description = '';
    public $special_instructions = '';
    public $safety_requirements = '';
    public $estimated_start_time = '';
    public $estimated_completion_time = '';
    public $assigned_technician_id = '';
    public $quality_check_required = true;
    public $customer_notification_required = true;
    public $notes = '';
    
    public $tasks = [];

    protected $rules = [
        'work_description' => 'required|string',
        'estimated_start_time' => 'required|date|after:now',
        'estimated_completion_time' => 'required|date|after:estimated_start_time',
        'assigned_technician_id' => 'required|exists:users,id',
        'tasks.*.task_name' => 'required|string',
        'tasks.*.estimated_duration' => 'required|numeric|min:0.5',
        'tasks.*.required_skills' => 'nullable|string',
    ];

    public function mount(Estimate $estimate)
    {
        $this->estimate = $estimate->load([
            'jobCard.customer',
            'jobCard.vehicle',
            'diagnosis',
            'lineItems'
        ]);

        $this->work_description = "Perform repairs as per approved estimate #{$estimate->estimate_number}";
        $this->estimated_start_time = now()->addDay()->format('Y-m-d\TH:i');
        $this->estimated_completion_time = now()->addDays(3)->format('Y-m-d\TH:i');
        
        // Initialize tasks from estimate line items
        $this->initializeTasks();
    }

    public function initializeTasks()
    {
        foreach ($this->estimate->lineItems as $item) {
            if ($item->type === 'labor') {
                $this->tasks[] = [
                    'task_name' => $item->description,
                    'task_description' => $item->description,
                    'estimated_duration' => $item->labor_hours ?? 1,
                    'required_skills' => '',
                    'safety_requirements' => '',
                    'status' => 'pending',
                ];
            }
        }
    }

    public function addTask()
    {
        $this->tasks[] = [
            'task_name' => '',
            'task_description' => '',
            'estimated_duration' => 1,
            'required_skills' => '',
            'safety_requirements' => '',
            'status' => 'pending',
        ];
    }

    public function removeTask($index)
    {
        unset($this->tasks[$index]);
        $this->tasks = array_values($this->tasks);
    }

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

        // Generate work order number
        $branchCode = $this->estimate->jobCard->branch_code;
        $lastWONumber = WorkOrder::where('work_order_number', 'like', $branchCode . '/WO%')
            ->whereYear('created_at', now()->year)
            ->count();
        $workOrderNumber = $branchCode . '/WO' . str_pad($lastWONumber + 1, 4, '0', STR_PAD_LEFT);

        $workOrder = WorkOrder::create([
            'work_order_number' => $workOrderNumber,
            'job_card_id' => $this->estimate->job_card_id,
            'estimate_id' => $this->estimate->id,
            'service_coordinator_id' => auth()->id(),
            'assigned_technician_id' => $this->assigned_technician_id,
            'priority' => $this->estimate->jobCard->priority,
            'status' => 'scheduled',
            'work_description' => $this->work_description,
            'special_instructions' => $this->special_instructions,
            'safety_requirements' => $this->safety_requirements,
            'estimated_start_time' => $this->estimated_start_time,
            'estimated_completion_time' => $this->estimated_completion_time,
            'quality_check_required' => $this->quality_check_required,
            'customer_notification_required' => $this->customer_notification_required,
            'notes' => $this->notes,
        ]);

        // Create tasks
        foreach ($this->tasks as $task) {
            WorkOrderTask::create([
                'work_order_id' => $workOrder->id,
                'task_name' => $task['task_name'],
                'task_description' => $task['task_description'],
                'estimated_duration' => $task['estimated_duration'],
                'required_skills' => $task['required_skills'],
                'safety_requirements' => $task['safety_requirements'],
                'status' => 'pending',
            ]);
        }

        // Update job card status
        $this->estimate->jobCard->update(['status' => 'work_order_created']);

        session()->flash('message', 'Work Order created successfully!');
        return redirect()->route('work-orders.show', $workOrder);
    }

    public function getTechniciansProperty()
    {
        return User::whereIn('role', ['technician', 'service_coordinator'])
            ->where('status', 'active')
            ->orderBy('name')
            ->get();
    }

    public function render()
    {
        return view('livewire.work-orders.create', [
            'technicians' => $this->technicians
        ]);
    }
}
