<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

trait StationDataFilter
{
    /**
     * Apply station-based filtering to a query
     */
    protected function applyStationFilter(Builder $query, string $stationColumn = 'station_id'): Builder
    {
        $user = Auth::user();

        // Admin users and high-ranking officers see all data
        if (!$user || !$user->is_officer || $user->hasMultiStationAccess()) {
            return $query;
        }

        // Regular officers only see data from their station
        return $query->where($stationColumn, $user->station_id);
    }

    /**
     * Apply station-based filtering to cases
     */
    protected function getFilteredCases(): Builder
    {
        $user = Auth::user();
        return $user->getAccessibleCases();
    }

    /**
     * Apply station-based filtering to officers
     */
    protected function getFilteredOfficers(): Builder
    {
        $user = Auth::user();
        return $user->getAccessibleOfficers();
    }

    /**
     * Apply station-based filtering to evidence
     */
    protected function getFilteredEvidence(): Builder
    {
        $user = Auth::user();
        return $user->getAccessibleEvidence();
    }

    /**
     * Apply station-based filtering to bail applications
     */
    protected function getFilteredBailApplications(): Builder
    {
        $user = Auth::user();
        return $user->getAccessibleBailApplications();
    }

    /**
     * Check if current user can access specific station data
     */
    protected function canAccessStation(int $stationId): bool
    {
        $user = Auth::user();
        return $user ? $user->canAccessStationData($stationId) : false;
    }

    /**
     * Get stations accessible to current user
     */
    protected function getAccessibleStations(): Builder
    {
        $user = Auth::user();

        if (!$user || !$user->is_officer || $user->hasMultiStationAccess()) {
            return \App\Models\PoliceStation::query();
        }

        return \App\Models\PoliceStation::where('id', $user->station_id);
    }

    /**
     * Apply station filtering to any model that has a case relationship
     */
    protected function applyStationFilterThroughCase(Builder $query, string $caseRelation = 'caseRecord'): Builder
    {
        $user = Auth::user();

        // Admin users and high-ranking officers see all data
        if (!$user || !$user->is_officer || $user->hasMultiStationAccess()) {
            return $query;
        }

        // Regular officers only see data from cases in their station
        return $query->whereHas($caseRelation, function($q) use ($user) {
            $q->where('station_id', $user->station_id);
        });
    }
}
