<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Machine;
use App\Models\MaintenanceSchedule;
use App\Models\MaintenanceLog;

class MaintenanceController extends Controller
{
    public function index()
    {
        $schedules = MaintenanceSchedule::with('machine')->latest()->get();
        $logs = MaintenanceLog::with(['machine', 'technician'])->latest()->paginate(10);
        return view('maintenance.index', compact('schedules', 'logs'));
    }

    public function create(Request $request)
    {
        $machines = Machine::all();
        $type = $request->get('type', 'log'); // 'log' or 'schedule'
        return view('maintenance.create', compact('machines', 'type'));
    }

    public function store(Request $request)
    {
        if ($request->has('schedule_maintenance')) {
            return $this->storeSchedule($request);
        }
        return $this->storeLog($request);
    }

    private function storeSchedule(Request $request)
    {
        $request->validate([
            'machine_id' => 'required|exists:machines,id',
            'maintenance_type' => 'required|in:preventive,corrective,inspection',
            'scheduled_date' => 'required|date',
        ]);

        MaintenanceSchedule::create($request->all());

        return redirect()->route('maintenance.index')->with('success', 'Maintenance scheduled.');
    }

    private function storeLog(Request $request)
    {
        $request->validate([
            'machine_id' => 'required|exists:machines,id',
            'start_time' => 'required|date',
            'end_time' => 'nullable|date|after:start_time',
        ]);

        $downtime = 0;
        if ($request->end_time) {
            $start = new \Carbon\Carbon($request->start_time);
            $end = new \Carbon\Carbon($request->end_time);
            $downtime = $end->diffInMinutes($start);
        }

        MaintenanceLog::create(array_merge($request->all(), [
            'technician_id' => auth()->id() ?? 1,
            'downtime_minutes' => $downtime,
        ]));

        // Update machine status if needed
        $machine = Machine::find($request->machine_id);
        if (!$request->end_time) {
            $machine->update(['status' => 'maintenance']);
        } else {
            $machine->update(['status' => 'idle', 'last_maintenance_at' => now()]);
        }

        return redirect()->route('maintenance.index')->with('success', 'Maintenance log recorded.');
    }

    public function show(string $id)
    {
        // View specific log or schedule details
    }
}
