<?php

namespace App\Http\Controllers;

use App\Models\Appointment;
use App\Models\Client;
use App\Models\Product;
use Illuminate\Http\Request;

class TallerController extends Controller
{
    /**
     * Vista principal
     */
    public function index()
    {
        // Trabajos activos ordenados por fecha
        $jobs = Appointment::with('client')
            ->whereIn('status', ['pending', 'in_progress', 'ready']) // Entregados/historial no se muestra, implementar vista aparte
            ->orderBy('scheduled_at', 'asc')
            ->get();

        // Agrupado por estado para las columnas
        $pending = $jobs->where('status', 'pending');
        $inProgress = $jobs->where('status', 'in_progress');
        $ready = $jobs->where('status', 'ready');

        return view('taller.index', compact('pending', 'inProgress', 'ready'));
    }

    /**
     * Formulario para nuevo servicio
     */
    public function create()
    {
        $clients = Client::orderBy('name')->get();

        $products = Product::whereIn('type', ['accessory','spare', 'service'])
                        ->where('stock_quantity', '>', 0)
                        ->get(['id', 'name', 'price', 'stock_quantity']); // Solo campos necesarios

        return view('taller.create', compact('clients', 'products'));
    }

    /**
     * Guardar el servicio
     */
    public function store(Request $request)
    {
        $request->validate([
            'client_id' => 'required|exists:clients,id',
            'bike_model' => 'required|string',
            'problem_description' => 'required|string',
            'scheduled_at' => 'required|date',
            'estimated_cost' => 'nullable|numeric',
        ]);

        // Buscamos el cliente para copiar su teléfono
        $client = Client::find($request->client_id);

        Appointment::create([
            'client_id' => $request->client_id,
            'contact_phone' => $request->contact_phone ?? $client->phone,
            'bike_model' => $request->bike_model,
            'problem_description' => $request->problem_description,
            'parts_needed' => $request->parts_needed,
            'estimated_cost' => $request->estimated_cost,
            'scheduled_at' => $request->scheduled_at,
            'status' => 'pending', // Estado inicial: Pendiente
        ]);

        return redirect()->route('taller.index')->with('success', 'Bicicleta ingresada al taller correctamente.');
    }

    /**
     * Mover de estado
     */
    public function updateStatus(Request $request, Appointment $appointment)
    {
        $appointment->update(['status' => $request->status]);
        return back()->with('success', 'Estado actualizado.');
    }
}