<?php

namespace App\Http\Controllers\Admin;

use App\Models\Room;
use App\Models\Examiner;
use App\Models\Examination;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Client;
use App\Models\Region;

class ReportsController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:reports-examinations', ['only' => ['index']]);
        $this->middleware('permission:reports-examiners', ['only' => ['examiner']]);
        $this->middleware('permission:reports-rooms', ['only' => ['room']]);
        $this->middleware('permission:reports-clients', ['only' => ['room']]);
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        // Start building the query
        $query = Examination::with('client')
            ->where('make_from', 'examinations'); // keep the existing filter


        // Filter by status if provided
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        // Filter by date range if provided
        if ($request->has('start_date') && $request->has('end_date') && $request->start_date != '' && $request->end_date != '') {
            $query->whereBetween('created_at', [$request->start_date, $request->end_date]);
        }

        // Get the filtered reports
        $reports = $query->get();

        return view('admin.reports.index', compact('reports'));
    }


    public function examiner()
    {
        // جلب الفاحصين مع عد الفحوصات الخاصة بكل فاحص، ثم ترتيبهم حسب العدد
        $examiners = Examiner::withCount('examinations') // هنا نضيف عد الفحوصات
            ->orderByDesc('examinations_count')  // ترتيب الفاحصين بناءً على عدد الفحوصات (تنازلي)
            ->get();

        // إرجاع العرض مع الفاحصين المرتبين حسب عدد الفحوصات
        return view('admin.reports.examiners', compact('examiners'));
    }

    public function room()
    {
        $rooms = Room::withCount([
            'users', // Count users in each room
            'examinations as examinations_count', // Count examinations created by users in the room
        ])
            ->orderByDesc('users_count') // Order by users count
            ->get();

        return view('admin.reports.rooms', compact('rooms'));
    }


    public function clients(Request $request)
    {
        // Build the query with optional filters
        $query = Client::query();
        $cities = City::get();
        $regions = Region::get();


        // Filter by first_name
        if ($request->has('first_name') && $request->first_name != '') {
            $query->where('first_name', 'like', '%' . $request->first_name . '%');
        }

        // Filter by last_name
        if ($request->has('last_name') && $request->last_name != '') {
            $query->where('last_name', 'like', '%' . $request->last_name . '%');
        }

        // Filter by birth_date
        if ($request->has('birth_date') && $request->birth_date != '') {
            $query->where('birth_date', $request->birth_date);
        }

        // Filter by address
        if ($request->has('address') && $request->address != '') {
            $query->where('address', 'like', '%' . $request->address . '%');
        }

        // Filter by phone
        if ($request->has('phone') && $request->phone != '') {
            $query->where('phone', 'like', '%' . $request->phone . '%');
        }

        // Filter by city_id
        if ($request->has('city_id') && $request->city_id != '') {
            $query->where('city_id', $request->city_id);
        }

        // Filter by region_id
        if ($request->has('region_id') && $request->region_id != '') {
            $query->where('region_id', $request->region_id);
        }

        // Filter by country_code
        if ($request->has('country_code') && $request->country_code != '') {
            $query->where('country_code', $request->country_code);
        }

        // Filter by full_phone_number
        if ($request->has('full_phone_number') && $request->full_phone_number != '') {
            $query->where('full_phone_number', 'like', '%' . $request->full_phone_number . '%');
        }

        // Filter by gender
        if ($request->has('gender') && $request->gender != '') {
            $query->where('gender', $request->gender);
        }

        // Aggregate totals
        $totalClients = $query->count();
        $totalMen = $query->where('gender', 'male')->count();
        $totalWomen = $query->where('gender', 'female')->count();

        // Get the filtered clients
        $clients = $query->get();

        return view('admin.reports.client', compact('clients', 'totalClients', 'totalMen', 'totalWomen','cities','regions'));
    }






    public function filter_client(Request $request)
    {
        $query = Client::query();

        // Apply filters
        foreach ($request->all() as $key => $value) {
            if ($value != '') {
                if (in_array($key, ['first_name', 'last_name', 'address', 'phone', 'full_phone_number'])) {
                    $query->where($key, 'like', '%' . $value . '%');
                } else {
                    $query->where($key, $value);
                }
            }
        }

        $clients = $query->get();

        $totalClients = $clients->count();
        $totalMen = $clients->where('gender', 'male')->count();
        $totalWomen = $clients->where('gender', 'female')->count();
        $cities = City::get();
        $html = view('admin.reports.partials.clients_table', compact('clients','cities'))->render();

        return response()->json([
            'html' => $html,
            'total_clients' => $totalClients,
            'total_men' => $totalMen,
            'total_women' => $totalWomen,
            'cities' => $cities,
        ]);
    }



    public function filter(Request $request)
    {
        $query = Examination::query();

        // فلترة بالحالة
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        // فلترة بالتاريخ (من)
        if ($request->has('from_date') && $request->from_date != '') {
            $query->whereDate('created_at', '>=', $request->from_date);
        }

        // فلترة بالتاريخ (إلى)
        if ($request->has('to_date') && $request->to_date != '') {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

        // جلب البيانات المفلترة
        $reports = $query->get();

        // إرجاع محتوى الجدول
        return view('admin.reports.examination_search', compact('reports'))->render();
    }
}
