<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Service;
use App\Models\ServiceName;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalHierarchies;
use Illuminate\Support\Facades\Auth;

class TrackApplication extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:application.track-application')->only('index');
    }
    public function index(Request $request)
    {
        $applications = $this->fetchApplications($request);
        $authUser = Auth::user();
        $isUserRole = $authUser && $authUser->hasRole('User');

        return view('track-application.index', compact('applications','isUserRole'));
    }


    public function fetchApplications(Request $request)
    {
        $applications = collect();
        $authUser = Auth::user();
        $isUserRole = $authUser && $authUser->hasRole('User');

        $mobile = $request->mobile_no;
        $applicationNo = $request->application_no;
        $departmentId = $request->department_id;
        $fromDate = $request->from_date;
        $toDate = $request->to_date;

        // If no filters are provided, return empty
        if (!$mobile && !$applicationNo ) {
            return $applications;
        }
        // dd((!$mobile && !$applicationNo && !$isUserRole));

        // Get user ID (based on mobile or logged-in user)
        $userId = null;
        if ($mobile) {
            $user = User::where('mobile', $mobile)->first();
            if ($user) {
                $userId = $user->id;
            } else {
                return $applications; // No user found for given mobile
            }
        }
        if ($isUserRole) {
            $userId = $authUser->id;
        }

        // Fetch all service names having models
        $services = ServiceName::with('service')->whereNotNull('model')->get();

        foreach ($services as $service) {
            $modelClass = $service->model;
            $serviceId = $service->service_id;

            if (!class_exists($modelClass)) {
                continue;
            }

            // Build query using Eloquent
            $query = $modelClass::with([
                'statuses' => function ($q) use ($serviceId) {
                    $q->where('service_id', $serviceId)
                        ->with([
                            'approvalhierarchies.approver.roles',
                            'serviceName'
                        ]);
                }
            ])->whereHas('statuses', function ($q) use ($serviceId) {
                $q->where('service_id', $serviceId);
            });

            // Apply filters
            if ($applicationNo) {
                $query->where('application_no', $applicationNo);
            }
            if ($userId) {
                $query->where('user_id', $userId);
            }
            if ($fromDate) {
                $query->whereDate('created_at', '>=', $fromDate);
            }
            if ($toDate) {
                $query->whereDate('created_at', '<=', $toDate);
            }

            $records = $query->get();

            foreach ($records as $record) {
                $statusRecord = $record->statuses;
                // dd($statusRecord);
                $user = $record->user ?? User::find($record->user_id);

                // Get approval hierarchy info
                $approvals = $statusRecord?->approvalhierarchies ?? collect();
                // dd($approvals);
                $approvers = $approvals->map(function ($a) {
                    $roleName = $a->approver?->roles?->pluck('name')->join(', ') ?? '-';
                    $statusText = match ($a->status) {
                        1 => 'Approved',
                        2 => 'Rejected',
                        default => 'Pending',
                    };

                    return [
                        'name' => $a->approver?->name ?? '-',
                        'role' => $roleName,
                        'status' => $statusText,
                        'remark' => $a->remark,
                    ];
                })->toArray();
                $applications->push([
                    'application_no'  => $record->application_no ?? '-',
                    'applicant_name'  => $user->name ?? '-',
                    'mobile_no'       => $user->mobile ?? '-',
                    'department_name' => $service->service->name ?? '-',
                    'service_name'    => $service->service_name ?? '-',
                    'approvers'       => $approvers,
                    'status'          => match ($statusRecord?->status) {
                        1 => 'Approved',
                        2 => 'Rejected',
                        default => 'Pending',
                    },
                ]);
            }
        }

        return $applications->values();
    }

}
