<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Repair;
use Illuminate\Http\Request;
use Inertia\Inertia;

class RepairController extends Controller
{
    public function index()
    {
        $repairs = Repair::latest()->get();

        return Inertia::render('Admin/Pages/Repairs/Index', [
            'repairs' => $repairs,
        ]);
    }

    public function create()
    {
        return Inertia::render('Admin/Pages/Repairs/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'device_model' => 'required|string|max:255',
            'problem' => 'required|string',
            'charge_amount' => 'required|numeric|min:0',
            'status' => 'required|in:pending,done',
        ]);

        Repair::create([
            'customer_name' => $request->customer_name,
            'phone_number' => $request->phone_number,
            'device_model' => $request->device_model,
            'problem' => $request->problem,
            'charge_amount' => $request->charge_amount,
            'status' => $request->status,
            'date' => today(),
        ]);

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

    public function edit(Repair $repair)
    {
        return Inertia::render('Admin/Pages/Repairs/Edit', [
            'repair' => $repair,
        ]);
    }

    public function update(Request $request, Repair $repair)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'device_model' => 'required|string|max:255',
            'problem' => 'required|string',
            'charge_amount' => 'required|numeric|min:0',
            'status' => 'required|in:pending,done',
        ]);

        $repair->update($request->all());

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

    public function destroy(Repair $repair)
    {
        $repair->delete();

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