<?php

namespace App\Http\Controllers;
use App\Utilities\ApiCalls;
use Session;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use App\Models;
use Illuminate\Support\Facades\Log;


class AdminController extends Controller
{
    public function index()
    {
        //dd(session('current_user')); //"ua_position" => "district-ppd-head" "user_type" => "district_user"

        if (session('current_user.user_type') == 'district_user') {
            $users_url = "user_mgt/get_all_users_by_district.php";
            $data = ['district_id' => session('current_user.district_id'), 'api_token' => env('LUPMISAPIKEY')];
        }
        elseif(session('current_user.user_type') == 'regional_user'){
            $users_url = "user_mgt/get_all_users_by_district.php";
            $data = ['region_id' => session('region_id'), 'api_token' => env('LUPMISAPIKEY')];
        }
        elseif(session('current_user.user_type') == 'national_luspa'){
            $users_url = "user_mgt/get_all_users.php";
            $data = ['api_token' => env('LUPMISAPIKEY')];
        }
        else{
           $users_url = "user_mgt/get_all_users.php"; 
           $data = ['api_token' => env('LUPMISAPIKEY') ];
        }

        $result = ApiCalls::CurlPost(json_encode($data), $users_url);
        /*
        $users_arr = json_decode($result, true);
        dump($users_arr);
        if ($users_arr == null || $users_arr['success'] == false || $users_arr['status'] == 'error') {
            Log::info(session('current_user.username') . " tried accessing Admin/home and got empty or no success users_arr");
            return redirect()->back()->withErrors('Your request cannot be handled at this time. Try again later');
        }
        */

        try {
            $usersArr = json_decode($result, true, 512, JSON_THROW_ON_ERROR);
        } 
        catch (\JsonException $e) {
            Log::warning('Admin/home API returned invalid JSON', [
                'user' => session('current_user.username'),
                'json_error' => $e->getMessage(),
            ]);

            return redirect()->back()
                ->withErrors(['api' => 'Your request cannot be handled at this time. Try again later.']);
        }

        if (!is_array($usersArr) || ($usersArr['success'] ?? null) === false || strtolower((string) ($usersArr['status'] ?? '')) === 'error') {
            Log::warning('Admin/home API returned an unsuccessful response', [
                'user' => session('current_user.username'),
                'success' => $usersArr['success'] ?? 'missing',
                'status' => $usersArr['status'] ?? 'missing',
            ]);
            return redirect()->back()
                ->withErrors(['api' => 'Your request cannot be handled at this time. Try again later.']);
        }


        $regions_url = "user_mgt/get_all_regions.php";
        $data = ['api_token' => env('LUPMISAPIKEY')];
        $result = ApiCalls::CurlPost(json_encode($data), $regions_url);
        $regions_arr = json_decode($result, true);
        if ($regions_arr == null || $regions_arr['success'] == false) {
            Log::info(session('current_user.username') . " tried accessing Admin/home and got empty or no success region");
            return redirect()->back()->withErrors('Your request cannot be handled at this time. Try again later');
        }


        $users = collect($users_arr['data']);
         // dd($users->sortBy('ua_id'));
        // dump($users);
        if (request()->has('search') && request()->search != '') {
            $search = strtolower(request()->search);
            
            $users = $users->filter(function($u) use ($search) {
                $name = strtolower($u['full_name'] ?? '');
                $email = strtolower($u['email'] ?? '');
                $username = strtolower($u['username'] ?? '');
                $phone = strtolower($u['phone'] ?? '');
                $ua_position = strtolower($u['ua_position'] ?? '');
                $allowed_apps = strtolower($u['allowed_apps'] ?? '');
                
                return str_contains($name, $search) || 
                       str_contains($email, $search) || 
                       str_contains($username, $search) ||
                       str_contains($phone, $search) ||
                       str_contains($ua_position, $search) ||
                       str_contains($allowed_apps, $search);
            });
        }
        $user_type_arr = [
            'district_user' => 'District User', 
            'regional_user' => 'Regional User',
            'national_user' => 'National User'
        ];
        $nationalUsers = $users->filter(function($u) {
            $type = trim(strtolower((string)($u['user_type'] ?? '')));
            $position = trim(strtolower((string)($u['ua_position'] ?? '')));
            
            // Check if either the type OR the position contains 'national'
            return str_contains($type, 'national') || str_contains($position, 'national');
        });

        $regionalUsers = $users->filter(function($u) {
            $type = trim(strtolower((string)($u['user_type'] ?? '')));
            $position = trim(strtolower((string)($u['ua_position'] ?? '')));
            
            return str_contains($type, 'regional') || str_contains($position, 'regional');
        });

        $districtUsers = $users->reject(function($u) {
            $type = trim(strtolower((string)($u['user_type'] ?? '')));
            $position = trim(strtolower((string)($u['ua_position'] ?? '')));
            
            $isNational = str_contains($type, 'national') || str_contains($position, 'national');
            $isRegional = str_contains($type, 'regional') || str_contains($position, 'regional');            
            return $isNational || $isRegional;
        });
        $paginatedDistrict = $this->paginateCollection($districtUsers, 10, 'district_page');
        $paginatedRegional = $this->paginateCollection($regionalUsers, 10, 'regional_page');
        $paginatedNational = $this->paginateCollection($nationalUsers, 10, 'national_page');
  
        return view('admin.home_cats', [
            'page_title' => 'User Admin',
            'regions_arr' => $regions_arr['data'],
            'user_type_arr' => $user_type_arr,
            'nationalUsers' => $paginatedNational,
            'regionalUsers' => $paginatedRegional,
            'districtUsers' => $paginatedDistrict,
            'totalUsers' => $users->count()
        ]);

    }
    public function indexSingle(){
        if (session('current_user.user_type') == 'district_user' || session('current_user.user_type') == 'District User' ) {
            $users_url = "user_mgt/get_all_users_by_district.php";
            $data = ['district_id' => session('current_user.district_id'), 'api_token' => env('LUPMISAPIKEY')];
        }
        elseif(session('current_user.user_type') == 'regional_user'){
            $users_url = "user_mgt/get_all_users_by_district.php";
            $data = ['region_id' => session('region_id'), 'api_token' => env('LUPMISAPIKEY')];
        }
        else{
           $users_url = "user_mgt/get_all_users.php"; 
           $data = ['api_token' => env('LUPMISAPIKEY') ];
        }
        $result = ApiCalls::CurlPost(json_encode($data), $users_url);
        $users_arr = json_decode($result, true);
        // dump($users_arr);
        if ($users_arr == null || $users_arr['success'] == false) {
            return redirect()->back()->withErrors('Your request cannot be handled at this time. Try again later');
        }

        $regions_url = "user_mgt/get_all_regions.php";
        $data = ['api_token' => env('LUPMISAPIKEY')];
        $result = ApiCalls::CurlPost(json_encode($data), $regions_url);
        $regions_arr = json_decode($result, true);
        if ($regions_arr == null || $regions_arr['success'] == false) {
            return redirect->back()->withErrors('Your request cannot be handled at this time. Try again later');
        }

        $perPage = 15;
        $search = request()->input('search');
        if ($search) {
            $filteredData = collect($users_arr['data'])->filter(function ($item) use ($search) {
                // Adjust fields to search in (e.g., 'title', 'category')
                return str_contains(strtolower($item['full_name']), strtolower($search)) || 
                       str_contains(strtolower($item['email']), strtolower($search)) || 
                       str_contains(strtolower($item['username']), strtolower($search)) ||
                       str_contains(strtolower($item['phone']), strtolower($search)) ||
                       str_contains(strtolower($item['allowed_apps']), strtolower($search)) ||
                       str_contains(strtolower($item['ua_position']), strtolower($search)) ||
                       str_contains(strtolower($item['phone']), strtolower($search));
            })->values()->all(); // Reset array keys
        } else {
            $filteredData = $users_arr['data'];
        }

        $currentPage = LengthAwarePaginator::resolveCurrentPage() ?: 1;
        $offset = ($currentPage - 1) * $perPage;

        $currentPageItems = array_slice($filteredData, $offset, $perPage);
        $paginatedItems = new LengthAwarePaginator(
            $currentPageItems,
            count($filteredData),    
            $perPage,          
            $currentPage,      
            ['path' => request()->url(), 'query' => request()->query()]
        );
        // dd($paginatedItems);
        $user_type_arr = [
            'district_user' => 'District User', 
            'regional_user' => 'Regional User',
            'national_user' => 'National User'
        ];
        // dump($users_arr['data']);
        $data = [
            'page_title' => 'User Admin',
            'users_arr' => $users_arr['data'],
            'regions_arr' => $regions_arr['data'],
            'user_type_arr' => $user_type_arr,
            'items' => $paginatedItems
        ];

        // return view('admin.home_new', $data); 
        return view('admin.paginated', $data);
        // return view('admin.home', $data);

    }
    
    public function districtparams(){
        /*
        $url = "user_mgt/get_district_parameters.php";
        $data = json_encode([
            'district_id' => 171,
            'api_token' => env('LUPMISAPIKEY')
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);
        dd($result);
        */

        $data = [
            'page_title' => "District Parameters"
        ];
        return view('admin.district_params', $data);
    }
    public function getDistrictSettingsJson()
    {   
        $districtid = session('current_user.district_id');
        
        $settings = Models\DistrictSetting::where('district_id', $districtid)->first(); 

        return response()->json([
            'success' => true,
            'data' => $settings
        ]);
    }
    public function updateDistrictSettings(Request $request)
    {
        $validated = $request->validate([
            'region_name' => 'required|string',
            'district_name' => 'required|string',
            'assembly_type' => 'required|in:district,municipal,metropolitan',
            'abbreviation' => 'required|string|max:20',
            'contact_phone' => 'required|string|max:20',
            'contact_email' => 'required|email',
            'outgoing_email' => 'required|email',
            'display_name' => 'required|string',
            'sms_sender_name' => 'required|string|max:20',
        ]);
        $districtid = session('current_user.district_id');
        Models\DistrictSetting::updateOrCreate(['district_id' => $districtid], $validated);

        return response()->json([
            'success' => true,
            'message' => 'Settings saved successfully'
        ]);
    }
    public function luspaparams(){
         $data = [
            'page_title' => "Page Under Development"
        ];
        return view('common.notready', $data);
    }
    public function feefixing(){
         $data = [
            'page_title' => "Page Under Development"
        ];
        return view('common.notready', $data);
    }
    public function districtsettings(){

         $data = [
            'page_title' => "District Settings"
        ];
        return view('admin.district_settings', $data);
    }
    public function systempermissions(){
        $user_group_matrix = Models\UserGroupMatrix::get();
        // dd($user_group_matrix);
         $data = [
            "page_title" => "System Permissions",
            "user_group_matrix" => $user_group_matrix
        ];
        return view('admin.system-permissions', $data);
    }
    public function districts($reqion_id){
       // return response()->json(['request' => $reqion_id]);
        $url = "user_mgt/get_district_by_region_id.php";
        $data = json_encode([
            'region_id' => $reqion_id,
            'api_token' => env('LUPMISAPIKEY')
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $results = json_decode($result, true);

        $result = ['code' => 1, 'districts' => $results['data']];
        if (request()->expectsJson()) {
            return response()->json($result);
        }
        $data = [
            'page_title' => 'Not Ready'
        ];
        return view('common.notready', $data);
    }

    public function reports(){
         $data = [
            'page_title' => "Page Under Development"
        ];
        return view('common.notready', $data);
    }
    /**
     * Manually paginate a collection.
     */
    private function paginateCollection(Collection $items, $perPage = 10, $pageName = 'page')
    {
        // 1. Get the current page from the URL (e.g., ?district_page=2)
        $page = LengthAwarePaginator::resolveCurrentPage($pageName);
        
        // 2. Slice the collection to get only the items for the current page
        $currentPageItems = $items->slice(($page - 1) * $perPage, $perPage)->values();

        // 3. Create the paginator instance
        $paginator = new LengthAwarePaginator(
            $currentPageItems, 
            $items->count(), 
            $perPage, 
            $page,
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => $pageName,
            ]
        );

        // Keep any other query parameters in the URL (like search keywords)
        return $paginator->withQueryString();
    }
}
