<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\HiringTrend;
use App\Models\Analytics;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Throwable;

class AnalyticsController extends Controller
{
    public function currentMonthStats(Request $request)
    {
        $companyId = $request->input('company_id', null);        // For a specific company
        $newHires = Analytics::getNewHire($companyId);
        $clearance = Analytics::getNewClearance($companyId);
        $promotion = Analytics::getNewPromotion($companyId);
        $regularization = Analytics::getNewRegularization($companyId);

        // Return response
        return response()->json([
            'new_hires' => $newHires,
            'promotion' => $promotion,
            'regularization' => $regularization,
            'clearance' => $clearance,
        ], 200);
    }

    public function hiringTrend(Request $request)
    {
        $year = $request->input('year', Carbon::now()->year);
        $companyId = $request->input('company_id', null);
        $dealershipId = $request->input('dealership_id', null);

        $data = HiringTrend::getTrend($year, $companyId, $dealershipId);

        return response()->json([
            'year' => $year,
            'data' => $data,
        ], 200);
    }
    public function attendanceSummary(Request $request)
{
    // --- Date range: current month by default ---
    $start = $request->input('date_start', Carbon::now()->startOfMonth()->toDateString());
    $end   = $request->input('date_end', Carbon::now()->endOfMonth()->toDateString());

    // --- Load employees with computed attendance (handled in model) ---
    $employees = Employee::withAttendancePercentage($start, $end)
        ->when($request->filled('company_id'), fn($q) => $q->where('company_id', $request->company_id))
        ->when($request->filled('dealership_id'), fn($q) => $q->where('dealer_id', $request->dealership_id))
        ->when($request->filled('department_id'), fn($q) => $q->where('department_id', $request->department_id))
        ->load([
            'company:id,name',
            'dealership:id,name',
            'department:id,name',
        ]);

    // --- Company summary ---
    $companySummary = $employees
        ->groupBy('company_id')
        ->map(function ($group) {
            $companyName = optional($group->first()->company)->name ?? 'Unknown';
            return [
                'name' => $companyName,
                'attendance' => round($group->avg('attendance_percentage'), 2),
            ];
        })
        ->values();

    // --- Dealership summary ---
    $dealershipSummary = $employees
        ->groupBy('dealer_id')
        ->map(function ($group) {
            $dealershipName = optional($group->first()->dealership)->name ?? 'Unknown';
            return [
                'name' => $dealershipName,
                'attendance' => round($group->avg('attendance_percentage'), 2),
            ];
        })
        ->values();

    // --- Department summary ---
    if ($request->filled('department_id')) {
        // Specific department only
        $departmentSummary = collect([[
            'name' => $employees->first()->department?->name ?? 'No Department',
            'attendance' => round($employees->avg('attendance_percentage'), 2),
        ]]);
    } else {
        // Grouped by active departments only (those with employees)
        $departmentSummary = $employees
            ->groupBy('department_id')
            ->map(function ($group) {
                $deptName = optional($group->first()->department)->name ?? 'Unknown';
                return [
                    'name' => $deptName,
                    'attendance' => round($group->avg('attendance_percentage'), 2),
                ];
            })
            ->values();
    }

    // --- Employee list ---
    $employeeList = $employees->map(fn($emp) => [
        'emp_id' => $emp->employee_id,
        'name' => $emp->lastname . ', ' . $emp->firstname,
        'department_id' => $emp->department_id,
        'department_name' => $emp->department?->name,
        'attendance_percentage' => $emp->attendance_percentage,
        'date_hired' => $emp->date_hired,
        'date_resign' => $emp->date_resign,
        'attendance_period' => $emp->attendance_period ?? null, // optional debug info from model
    ]);

    // --- Return JSON response ---
    return response()->json([
        'filters' => [
            'company_id' => $request->company_id,
            'dealership_id' => $request->dealership_id,
            'department_id' => $request->department_id,
        ],
        'date_range' => [
            'start' => $start,
            'end' => $end,
        ],
        'company' => $companySummary,
        'dealership' => $dealershipSummary,
        'department' => $departmentSummary,
        'employees' => $employeeList,
    ]);
}

public function headCountSummary(Request $request)
{
    $today = date('Y-m-d');

    // Base query with relationships
    $query = Employee::with(['personal_information', 'department']);

    // Optional filters
    if ($request->has('company_id')) {
        $query->where('company_id', $request->company_id);
    }

    if ($request->has('dealer_id')) {
        $query->where('dealer_id', $request->dealership_id);
    }

    // Active employees
    $query->whereDate('date_hired', '<=', $today)
        ->where(function ($q) use ($today) {
            $q->whereNull('date_resign')
                ->orWhereDate('date_resign', '>=', $today);
        });

    $employees = $query->get();

    // Initialize summaries
    $summary = [];

    // Group employees by department
    $departments = $employees->groupBy('department_id');

    foreach ($departments as $deptId => $deptEmployees) {
        $departmentName = optional($deptEmployees->first()->department)->name ?? 'No Department';

        // Headcount by gender (normalized)
        $genderCounts = [
            'Male' => 0,
            'Female' => 0,
            'Not Specified' => 0,
        ];

        foreach ($deptEmployees as $emp) {
            $gender = optional($emp->personal_information)->gender;
            $gender = match (strtoupper(trim($gender))) {
                'M', 'MALE' => 'Male',
                'F', 'FEMALE' => 'Female',
                default => 'Not Specified',
            };
            $genderCounts[$gender]++;
        }

        // --- Gender percentages ---
        $deptTotal = $deptEmployees->count();
        $genderPercentages = [];
        foreach ($genderCounts as $gender => $count) {
            $genderPercentages[$gender] = $deptTotal > 0
                ? round(($count / $deptTotal) * 100, 2)
                : 0;
        }

        // Headcount by age groups
        $ageGroups = [
            '18–25' => 0,
            '26–35' => 0,
            '36–45' => 0,
            '46–55' => 0,
            '56+'   => 0,
        ];

        $deptAgeSum = 0;
        $deptAgeCount = 0;

        foreach ($deptEmployees as $emp) {
            $birthDate = optional($emp->personal_information)->birth_date;
            if (!$birthDate) continue;

            $age = Carbon::parse($birthDate)->age;
            $deptAgeSum += $age;
            $deptAgeCount++;

            if ($age >= 18 && $age <= 25) $ageGroups['18–25']++;
            elseif ($age >= 26 && $age <= 35) $ageGroups['26–35']++;
            elseif ($age >= 36 && $age <= 45) $ageGroups['36–45']++;
            elseif ($age >= 46 && $age <= 55) $ageGroups['46–55']++;
            else $ageGroups['56+']++;
        }

        $deptAverageAge = $deptAgeCount > 0 ? round($deptAgeSum / $deptAgeCount, 1) : null;

        $summary[$departmentName] = [
            'gender' => [
                'counts' => $genderCounts,
                'percentages' => $genderPercentages,
            ],
            'age_groups' => $ageGroups,
            'total' => $deptTotal,
            'average_age' => $deptAverageAge,
        ];
    }

    // --- Overall totals ---
    $overallGender = [
        'Male' => 0,
        'Female' => 0,
        'Not Specified' => 0,
    ];

    $overallAgeGroups = [
        '18–25' => 0,
        '26–35' => 0,
        '36–45' => 0,
        '46–55' => 0,
        '56+'   => 0,
    ];

    $ageSum = 0;
    $ageCount = 0;

    foreach ($employees as $emp) {
        // Gender normalization
        $gender = optional($emp->personal_information)->gender;
        $gender = match (strtoupper(trim($gender))) {
            'M', 'MALE' => 'Male',
            'F', 'FEMALE' => 'Female',
            default => 'Not Specified',
        };
        $overallGender[$gender]++;

        // Age grouping
        $birthDate = optional($emp->personal_information)->birth_date;
        if (!$birthDate) continue;

        $age = Carbon::parse($birthDate)->age;
        $ageSum += $age;
        $ageCount++;

        if ($age >= 18 && $age <= 25) $overallAgeGroups['18–25']++;
        elseif ($age >= 26 && $age <= 35) $overallAgeGroups['26–35']++;
        elseif ($age >= 36 && $age <= 45) $overallAgeGroups['36–45']++;
        elseif ($age >= 46 && $age <= 55) $overallAgeGroups['46–55']++;
        else $overallAgeGroups['56+']++;
    }

    $overallTotal = $employees->count();
    $averageAge = $ageCount > 0 ? round($ageSum / $ageCount, 1) : null;

    // --- Overall gender percentages ---
    $overallGenderPercentages = [];
    foreach ($overallGender as $gender => $count) {
        $overallGenderPercentages[$gender] = $overallTotal > 0
            ? round(($count / $overallTotal) * 100, 2)
            : 0;
    }

    return response()->json([
        'overall' => [
            'gender' => [
                'counts' => $overallGender,
                'percentages' => $overallGenderPercentages,
            ],
            'age_groups' => $overallAgeGroups,
            'total' => $overallTotal,
            'average_age' => $averageAge,
        ],
        'by_department' => $summary,
    ]);
}



}
