<?php

namespace App\Http\Controllers;

use App\Models\MaintenanceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MaintenanceRequestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $maintenanceRequests = MaintenanceRequest::with(['elevator', 'customer', 'assignedTeam', 'assignedUser'])
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        return view('maintenance.requests.index', compact('maintenanceRequests'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('maintenance.requests.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'elevator_id' => 'required|exists:elevators,id',
            'customer_id' => 'required|exists:customers,id',
            'company_id' => 'required|exists:companies,id',
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'problem_details' => 'nullable|string',
            'priority' => 'required|in:low,medium,high,urgent',
            'status' => 'required|in:pending,assigned,in_progress,completed,cancelled',
            'requested_date' => 'required|date',
            'is_emergency' => 'boolean',
            'branch_id' => 'nullable|exists:branches,id',
            'assigned_team_id' => 'nullable|exists:maintenance_teams,id',
            'assigned_user_id' => 'nullable|exists:users,id',
        ]);

        // Generate a unique request number
        $latestRequest = MaintenanceRequest::latest()->first();
        $requestNumber = 'MR-' . date('Ymd') . '-' . sprintf('%04d', $latestRequest ? (intval(substr($latestRequest->request_number, -4)) + 1) : 1);

        $maintenanceRequest = new MaintenanceRequest();
        $maintenanceRequest->company_id = $request->company_id;
        $maintenanceRequest->branch_id = $request->branch_id;
        $maintenanceRequest->elevator_id = $request->elevator_id;
        $maintenanceRequest->customer_id = $request->customer_id;
        $maintenanceRequest->request_number = $requestNumber;
        $maintenanceRequest->title = $request->title;
        $maintenanceRequest->description = $request->description;
        $maintenanceRequest->problem_details = $request->problem_details;
        $maintenanceRequest->priority = $request->priority;
        $maintenanceRequest->status = $request->status;
        $maintenanceRequest->requested_date = $request->requested_date;
        $maintenanceRequest->is_emergency = $request->is_emergency ?? false;
        $maintenanceRequest->created_by = Auth::id();

        if ($request->has('assigned_team_id')) {
            $maintenanceRequest->assigned_team_id = $request->assigned_team_id;
        }

        if ($request->has('assigned_user_id')) {
            $maintenanceRequest->assigned_user_id = $request->assigned_user_id;
        }

        $maintenanceRequest->save();

        return redirect()->route('maintenance-requests.index')
            ->with('success', 'تم إنشاء طلب الصيانة بنجاح');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\MaintenanceRequest  $maintenanceRequest
     * @return \Illuminate\Http\Response
     */
    public function show(MaintenanceRequest $maintenanceRequest)
    {
        $maintenanceRequest->load(['elevator', 'customer', 'assignedTeam', 'assignedUser', 'creator']);

        return view('maintenance.requests.show', compact('maintenanceRequest'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\MaintenanceRequest  $maintenanceRequest
     * @return \Illuminate\Http\Response
     */
    public function edit(MaintenanceRequest $maintenanceRequest)
    {
        return view('maintenance.requests.edit', compact('maintenanceRequest'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\MaintenanceRequest  $maintenanceRequest
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, MaintenanceRequest $maintenanceRequest)
    {
        $request->validate([
            'elevator_id' => 'required|exists:elevators,id',
            'customer_id' => 'required|exists:customers,id',
            'company_id' => 'required|exists:companies,id',
            'title' => 'required|string|max:255',
            'description' => 'required|string',
            'problem_details' => 'nullable|string',
            'priority' => 'required|in:low,medium,high,urgent',
            'status' => 'required|in:pending,assigned,in_progress,completed,cancelled',
            'requested_date' => 'required|date',
            'scheduled_date' => 'nullable|date',
            'is_emergency' => 'boolean',
            'branch_id' => 'nullable|exists:branches,id',
            'assigned_team_id' => 'nullable|exists:maintenance_teams,id',
            'assigned_user_id' => 'nullable|exists:users,id',
        ]);

        $maintenanceRequest->company_id = $request->company_id;
        $maintenanceRequest->branch_id = $request->branch_id;
        $maintenanceRequest->elevator_id = $request->elevator_id;
        $maintenanceRequest->customer_id = $request->customer_id;
        $maintenanceRequest->title = $request->title;
        $maintenanceRequest->description = $request->description;
        $maintenanceRequest->problem_details = $request->problem_details;
        $maintenanceRequest->priority = $request->priority;
        $maintenanceRequest->status = $request->status;
        $maintenanceRequest->requested_date = $request->requested_date;
        $maintenanceRequest->scheduled_date = $request->scheduled_date;
        $maintenanceRequest->is_emergency = $request->is_emergency ?? false;

        if ($request->has('assigned_team_id')) {
            $maintenanceRequest->assigned_team_id = $request->assigned_team_id;
        }

        if ($request->has('assigned_user_id')) {
            $maintenanceRequest->assigned_user_id = $request->assigned_user_id;
        }

        // If status is completed, add completion date and notes
        if ($request->status === 'completed') {
            $maintenanceRequest->completed_date = now();
            if ($request->has('completion_notes')) {
                $maintenanceRequest->completion_notes = $request->completion_notes;
            }
        }

        $maintenanceRequest->save();

        return redirect()->route('maintenance-requests.index')
            ->with('success', 'تم تحديث طلب الصيانة بنجاح');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\MaintenanceRequest  $maintenanceRequest
     * @return \Illuminate\Http\Response
     */
    public function destroy(MaintenanceRequest $maintenanceRequest)
    {
        $maintenanceRequest->delete();

        return redirect()->route('maintenance-requests.index')
            ->with('success', 'تم حذف طلب الصيانة بنجاح');
    }
}
