<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\PoliceStation;
use App\Traits\StationDataFilter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class OfficerController extends Controller
{
    use StationDataFilter;

    /**
     * Display a listing of the officers.
     */
    public function index()
    {
        // Get officers filtered by station access
        $officers = $this->getFilteredOfficers()
            ->with('station')
            ->paginate(10);
            
        return view('officers.index', compact('officers'));
    }

    /**
     * Show the form for creating a new officer.
     */
    public function create()
    {
        // Get stations based on user access level
        $stations = Auth::user()->hasMultiStationAccess() ? 
            PoliceStation::where('is_active', true)->get() : 
            PoliceStation::where('id', Auth::user()->station_id)->where('is_active', true)->get();
            
        return view('officers.create', compact('stations'));
    }

    /**
     * Store a newly created officer in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8'],
            'rank' => ['nullable', 'string', 'max:100'],
            'badge_number' => ['nullable', 'string', 'max:50', 'unique:users,badge_number'],
            'station_id' => ['nullable', 'exists:police_stations,id'],
            'profile_picture' => ['nullable', 'image', 'max:2048'], // Max 2MB
        ]);

        $userData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'is_officer' => true,
            'rank' => $validated['rank'],
            'badge_number' => $validated['badge_number'],
            'station_id' => $validated['station_id'],
        ];
        
        // Handle profile picture upload
        if ($request->hasFile('profile_picture')) {
            $file = $request->file('profile_picture');
            $filename = time() . '_' . $file->getClientOriginalName();
            
            // Debug information
            logger()->info('File upload debug:', [
                'has_file' => $request->hasFile('profile_picture'),
                'original_name' => $file->getClientOriginalName(),
                'file_size' => $file->getSize(),
                'file_extension' => $file->getClientOriginalExtension(),
                'destination_path' => 'profile_pictures/' . $filename
            ]);
            
            // Store the file in the public disk
            $file->storeAs('profile_pictures', $filename, 'public');
            $userData['profile_picture'] = $filename;
        } else {
            logger()->warning('No profile picture file in request');
            logger()->info('Request data:', $request->all());
        }

        $user = User::create($userData);

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

    /**
     * Display the specified officer.
     */
    public function show(User $officer)
    {
        if (!$officer->is_officer) {
            return redirect()->route('officers.index')
                ->with('error', 'User is not an officer.');
        }
        
        // Check if user can access this officer's station data
        if (!Auth::user()->canAccessStationData($officer->station_id)) {
            return redirect()->route('officers.index')
                ->with('error', 'You do not have permission to view this officer.');
        }
        
        // Get cases where the officer is either the lead investigator or reporting officer
        // Apply station filtering to the cases as well
        $leadCases = $this->getFilteredCases()
            ->where('lead_investigator_id', $officer->id)
            ->latest()
            ->take(10)
            ->get();
            
        $reportingCases = $this->getFilteredCases()
            ->where('reporting_officer_id', $officer->id)
            ->latest()
            ->take(10)
            ->get();
        
        // Merge and sort cases by latest first
        $cases = $leadCases->merge($reportingCases)->sortByDesc('created_at')->take(10);

        return view('officers.show', compact('officer', 'cases'));
    }

    /**
     * Show the form for editing the specified officer.
     */
    public function edit(User $officer)
    {
        if (!$officer->is_officer) {
            return redirect()->route('officers.index')
                ->with('error', 'User is not an officer.');
        }
        
        // Check if user can access this officer's station data
        if (!Auth::user()->canAccessStationData($officer->station_id)) {
            return redirect()->route('officers.index')
                ->with('error', 'You do not have permission to edit this officer.');
        }

        // Get stations based on user access level
        $stations = Auth::user()->hasMultiStationAccess() ? 
            PoliceStation::where('is_active', true)->get() : 
            PoliceStation::where('id', Auth::user()->station_id)->where('is_active', true)->get();
            
        return view('officers.edit', compact('officer', 'stations'));
    }

    /**
     * Update the specified officer in storage.
     */
    public function update(Request $request, User $officer)
    {
        if (!$officer->is_officer) {
            return redirect()->route('officers.index')
                ->with('error', 'User is not an officer.');
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($officer->id)],
            'rank' => ['nullable', 'string', 'max:100'],
            'badge_number' => ['nullable', 'string', 'max:50', Rule::unique('users')->ignore($officer->id)],
            'station_id' => ['nullable', 'exists:police_stations,id'],
            'profile_picture' => ['nullable', 'image', 'max:2048'], // Max 2MB
        ]);

        // Only update password if provided
        if ($request->filled('password')) {
            $request->validate([
                'password' => ['string', 'min:8'],
            ]);
            $validated['password'] = Hash::make($request->password);
        }
        
        // Handle profile picture upload
        if ($request->hasFile('profile_picture')) {
            // Debug information
            logger()->info('Update method - File upload debug:', [
                'has_file' => $request->hasFile('profile_picture'),
                'original_name' => $request->file('profile_picture')->getClientOriginalName(),
                'file_size' => $request->file('profile_picture')->getSize(),
                'file_extension' => $request->file('profile_picture')->getClientOriginalExtension()
            ]);
            
            // Delete old profile picture if exists
            if ($officer->profile_picture) {
                $oldPicturePath = storage_path('app/public/profile_pictures/' . $officer->profile_picture);
                logger()->info('Old picture path: ' . $oldPicturePath . ', exists: ' . (file_exists($oldPicturePath) ? 'yes' : 'no'));
                
                // Also check in the private directory where files might have been saved incorrectly before
                $oldPrivatePicturePath = storage_path('app/private/public/profile_pictures/' . $officer->profile_picture);
                if (file_exists($oldPrivatePicturePath)) {
                    unlink($oldPrivatePicturePath);
                    logger()->info('Deleted old picture from private path: ' . $oldPrivatePicturePath);
                }
                
                if (file_exists($oldPicturePath)) {
                    unlink($oldPicturePath);
                    logger()->info('Deleted old picture from public path: ' . $oldPicturePath);
                }
            }
            
            $file = $request->file('profile_picture');
            $filename = time() . '_' . $file->getClientOriginalName();
            logger()->info('New filename: ' . $filename);
            
            // Store the file in the public disk
            $file->storeAs('profile_pictures', $filename, 'public');
            $validated['profile_picture'] = $filename;
        } else {
            logger()->warning('Update method - No profile picture file in request');
            logger()->info('Update method - Request data:', $request->all());
        }

        $officer->update($validated);

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

    /**
     * Remove the specified officer from storage.
     */
    public function destroy(User $officer)
    {
        if (!$officer->is_officer) {
            return redirect()->route('officers.index')
                ->with('error', 'User is not an officer.');
        }

        // Convert to regular user instead of deleting
        $officer->update([
            'is_officer' => false,
            'rank' => null,
            'badge_number' => null,
            'station_id' => null,
        ]);

        return redirect()->route('officers.index')
            ->with('success', 'Officer removed successfully.');
    }
    
    /**
     * Assign multiple officers to a station.
     */
    public function assignBatch()
    {
        // Get officers filtered by station access
        $officers = $this->getFilteredOfficers()->get();
        
        // Get stations based on user access level
        $stations = Auth::user()->hasMultiStationAccess() ? 
            PoliceStation::where('is_active', true)->get() : 
            PoliceStation::where('id', Auth::user()->station_id)->where('is_active', true)->get();
        
        return view('officers.assign-batch', compact('officers', 'stations'));
    }
    
    /**
     * Process batch assignment of officers to stations.
     */
    public function processBatchAssignment(Request $request)
    {
        $validated = $request->validate([
            'officer_ids' => ['required', 'array'],
            'officer_ids.*' => ['exists:users,id'],
            'station_id' => ['required', 'exists:police_stations,id'],
        ]);
        
        User::whereIn('id', $validated['officer_ids'])->update([
            'station_id' => $validated['station_id']
        ]);
        
        return redirect()->route('officers.index')
            ->with('success', 'Officers assigned to station successfully.');
    }
}
