<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\MaintenanceRecord;
use App\Models\Vehicle;

class MaintenanceController extends Controller
{
    public function index()
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        $records = MaintenanceRecord::with('vehicle')
            ->latest()
            ->get();

        return view('admin.maintenance.index', compact('records'));
    }

    public function create()
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        $vehicles = Vehicle::all();

        return view('admin.maintenance.create', compact('vehicles'));
    }

    public function store(Request $request)
    {
        if (auth()->user()->role != 'admin') {
            abort(403);
        }

        MaintenanceRecord::create([
            'vehicle_id' => $request->vehicle_id,
            'service_type' => $request->service_type,
            'service_date' => $request->service_date,
            'cost' => $request->cost,
            'vendor' => $request->vendor,
            'notes' => $request->notes,
        ]);

        Vehicle::where('id', $request->vehicle_id)
            ->update([
                'status' => 'maintenance'
            ]);

        return redirect('/admin/maintenance');
    }

public function complete(Request $request, $id)
{
    $record = MaintenanceRecord::findOrFail($id);

    $repairProof = null;

if ($request->hasFile('repair_proof')) {

    $repairProof = $request
        ->file('repair_proof')
        ->store('maintenance', 'public');

}

    $warehouseProof = null;

if ($request->hasFile('warehouse_proof')) {

    $warehouseProof = $request
        ->file('warehouse_proof')
        ->store('maintenance', 'public');

}

    $record->update([
        'maintenance_status' => 'completed',
        'completion_date' => $request->completion_date,
        'repair_proof' => $repairProof,
        'warehouse_proof' => $warehouseProof,
        'completion_notes' => $request->completion_notes
    ]);

    Vehicle::where(
        'id',
        $record->vehicle_id
    )->update([
        'status' => 'available'
    ]);

    return redirect('/admin/maintenance')
        ->with('success', 'Maintenance selesai.');
}
}