<?php

namespace App\Http\Controllers;

use App\Models\Dispatch;
use App\Models\DispatchUnit;
use App\Services\DispatchService;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class DispatchController extends Controller
{
    public function __construct(
        private DispatchService $dispatchService,
        private NotificationService $notificationService
    ) {}

    /**
     * Display a listing of dispatches
     */
    public function index(Request $request)
    {
        if (!Schema::hasTable('dispatches')) {
            $dispatches = $this->emptyPaginator();
            return view('dispatches.index', compact('dispatches'));
        }

        $query = Dispatch::with(['complaint', 'polsek', 'dispatcher', 'dispatchUnits.officer'])
            ->orderBy('created_at', 'desc');

        // Filter based on user role
        $user = $request->user();
        if ($user && $user->role === 'polsek' && $user->polsek_id) {
            $query->where('polsek_id', $user->polsek_id);
        }

        // Apply filters
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        if ($request->has('unit_type')) {
            $query->where('unit_type', $request->unit_type);
        }

        $dispatches = $query->paginate(20);

        return view('dispatches.index', compact('dispatches'));
    }

    /**
     * Display the specified dispatch
     */
    public function show(Dispatch $dispatch)
    {
        $dispatch->load([
            'complaint.location',
            'polsek',
            'dispatcher',
            'dispatchUnits.officer.user',
            'fieldReports',
        ]);

        return view('dispatches.show', compact('dispatch'));
    }

    /**
     * Accept dispatch
     */
    public function accept(Request $request, Dispatch $dispatch)
    {
        $user = $request->user();
        
        // Check if user is officer assigned to this dispatch
        $dispatchUnit = DispatchUnit::where('dispatch_id', $dispatch->id)
            ->whereHas('officer', function($q) use ($user) {
                $q->where('user_id', $user->id);
            })
            ->first();

        if (!$dispatchUnit) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $dispatchUnit->update([
            'status' => 'accepted',
            'accepted_at' => now(),
        ]);

        $dispatch->update([
            'status' => 'accepted',
            'accepted_at' => now(),
        ]);

        // Update officer status
        $dispatchUnit->officer->update(['status' => 'busy']);

        return response()->json([
            'success' => true,
            'message' => 'Dispatch accepted',
        ]);
    }

    /**
     * Complete dispatch
     */
    public function complete(Request $request, Dispatch $dispatch)
    {
        $user = $request->user();
        
        $dispatchUnit = DispatchUnit::where('dispatch_id', $dispatch->id)
            ->whereHas('officer', function($q) use ($user) {
                $q->where('user_id', $user->id);
            })
            ->first();

        if (!$dispatchUnit) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'description' => 'nullable|string',
            'photos' => 'nullable|array',
            'videos' => 'nullable|array',
        ]);

        // Create field report
        $dispatchUnit->officer->fieldReports()->create([
            'dispatch_id' => $dispatch->id,
            'status' => 'completed',
            'description' => $validated['description'] ?? null,
            'photos' => $validated['photos'] ?? null,
            'videos' => $validated['videos'] ?? null,
            'completed_at' => now(),
        ]);

        $dispatchUnit->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        // Check if all units completed
        $allCompleted = $dispatch->dispatchUnits()->where('status', '!=', 'completed')->count() === 0;
        
        if ($allCompleted) {
            $dispatch->update([
                'status' => 'completed',
                'completed_at' => now(),
            ]);

            $dispatch->complaint->update([
                'status' => 'completed',
                'resolved_at' => now(),
            ]);
        }

        // Update officer status
        $dispatchUnit->officer->update(['status' => 'available']);

        return response()->json([
            'success' => true,
            'message' => 'Dispatch completed',
        ]);
    }
}
