<?php

namespace App\Livewire\Timesheets;

use App\Models\Timesheet;
use App\Models\JobCard;
use App\Models\WorkOrderTask;
use Livewire\Component;

class Create extends Component
{
    public $job_card_id = '';
    public $work_order_task_id = '';
    public $task_type = 'diagnosis';
    public $task_description = '';
    public $start_time = '';
    public $end_time = '';
    public $duration_hours = 0;
    public $notes = '';
    public $tools_used = '';
    public $materials_used = '';
    public $completion_percentage = 0;
    public $status = 'in_progress';

    protected $rules = [
        'job_card_id' => 'required|exists:job_cards,id',
        'task_type' => 'required|in:diagnosis,repair,maintenance,inspection,other',
        'task_description' => 'required|string|max:500',
        'start_time' => 'required|date',
        'end_time' => 'nullable|date|after:start_time',
        'duration_hours' => 'nullable|numeric|min:0',
        'completion_percentage' => 'required|integer|min:0|max:100',
        'status' => 'required|in:scheduled,in_progress,completed,paused',
    ];

    public function mount()
    {
        $this->start_time = now()->format('Y-m-d\TH:i');
    }

    public function updatedEndTime()
    {
        if ($this->start_time && $this->end_time) {
            $start = \Carbon\Carbon::parse($this->start_time);
            $end = \Carbon\Carbon::parse($this->end_time);
            $this->duration_hours = $end->diffInHours($start, true);
        }
    }

    public function updatedJobCardId()
    {
        // Reset work order task when job card changes
        $this->work_order_task_id = '';
    }

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

        Timesheet::create([
            'job_card_id' => $this->job_card_id,
            'work_order_task_id' => $this->work_order_task_id ?: null,
            'technician_id' => auth()->id(),
            'task_type' => $this->task_type,
            'task_description' => $this->task_description,
            'start_time' => $this->start_time,
            'end_time' => $this->end_time,
            'duration_hours' => $this->duration_hours,
            'notes' => $this->notes,
            'tools_used' => $this->tools_used,
            'materials_used' => $this->materials_used,
            'completion_percentage' => $this->completion_percentage,
            'status' => $this->status,
        ]);

        session()->flash('message', 'Timesheet entry created successfully!');
        return redirect()->route('timesheets.index');
    }

    public function getJobCardsProperty()
    {
        return JobCard::with(['customer', 'vehicle'])
            ->whereNotIn('status', ['completed', 'cancelled'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function getWorkOrderTasksProperty()
    {
        if (!$this->job_card_id) {
            return collect();
        }

        return WorkOrderTask::whereHas('workOrder', function ($query) {
                $query->where('job_card_id', $this->job_card_id);
            })
            ->where('status', '!=', 'completed')
            ->get();
    }

    public function render()
    {
        return view('livewire.timesheets.create', [
            'jobCards' => $this->jobCards,
            'workOrderTasks' => $this->workOrderTasks,
        ]);
    }
}
