<?php

namespace App\Http\Controllers;

use App\Models\Request;
use App\Models\RequestType;
use Illuminate\Http\Request as HttpRequest;

class RequestController extends Controller
{
    public function index(HttpRequest $request)
    {
        $user = auth()->user();
        $query = Request::with(['user', 'requestType']);

        // Apply search filter
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('note', 'like', "%{$search}%")
                    ->orWhereHas('user', function ($q) use ($search) {
                        $q->where('name', 'like', "%{$search}%")
                            ->orWhere('email', 'like', "%{$search}%")
                            ->orWhere('phone', 'like', "%{$search}%");
                    });
            });
        }

        // Apply status filter
        if ($request->has('status') && !empty($request->status)) {
            $query->where('status', $request->status);
        }

        // Apply type filter
        if ($request->has('type') && !empty($request->type)) {
            $query->where('request_type_id', $request->type);
        }

        // Apply user role filter
        if (!$user->isAdmin() && !$user->isOperation()) {
            $query->where('user_id', $user->id);
        }

        $requests = $query->latest()->paginate(10);
        $requestTypes = RequestType::all();

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

    public function create()
    {
        if (!auth()->user()->isOwner()) {
            return redirect()->route('dashboard')->with('error', 'Only owners can create requests.');
        }

        $requestTypes = RequestType::all();
        return view('requests.create', compact('requestTypes'));
    }

    public function store(HttpRequest $request)
    {
        if (!auth()->user()->isOwner()) {
            return redirect()->route('dashboard')->with('error', 'Only owners can create requests.');
        }

        $validated = $request->validate([
            'request_type_id' => 'required|exists:request_types,id',
            'note' => 'required|string|min:10'
        ]);

        $newRequest = Request::create([
            'user_id' => auth()->id(),
            'request_type_id' => $validated['request_type_id'],
            'note' => $validated['note'],
            'status' => 'pending'
        ]);

        return redirect()->route('requests.index')
            ->with('success', 'Request created successfully.');
    }

    public function show(Request $request)
    {
        $user = auth()->user();
        if (!$user->isAdmin() && !$user->isOperation() && $request->user_id !== $user->id) {
            return redirect()->route('dashboard')->with('error', 'Unauthorized access.');
        }

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

    public function edit(Request $request)
    {
        $user = auth()->user();
        if (!$user->isAdmin() && !$user->isOperation()) {
            return redirect()->route('dashboard')->with('error', 'Only admins and operation users can edit requests.');
        }

        return view('requests.edit', compact('request'));
    }

    public function update(HttpRequest $httpRequest, Request $request)
    {
        $user = auth()->user();
        if (!$user->isAdmin() && !$user->isOperation()) {
            return redirect()->route('dashboard')->with('error', 'Only admins and operation users can update requests.');
        }

        $validated = $httpRequest->validate([
            'status' => 'required|in:pending,in_progress,completed,cancelled',
            'admin_note' => 'nullable|string'
        ]);

        $request->update([
            'status' => $validated['status'],
            'admin_note' => $validated['admin_note'],
            'completed_at' => $validated['status'] === 'completed' ? now() : null
        ]);

        return redirect()->route('requests.index')
            ->with('success', 'Request updated successfully.');
    }
}
