<?php 

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\EmployeeChangeSchedule;
use App\Models\EmployeeLeave;
use App\Models\EmployeeMonthlySchedule;
use App\Models\EmployeeOb;
use App\Models\EmployeeOffset;
use App\Models\EmployeeOffsetEarning;
use App\Models\EmployeeOvertime;
use App\Models\EmployeeTimeAdjustment;
use App\Models\EmployeeUndertime;
use App\Models\EmployeeWfh;
use App\Models\RoleCompanyAccess;
use App\Models\TimelogEdit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AttendanceRequestStatusController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $employeeId = $user->employees->employee_id;

        $data = [
            'leave' => $this->getStatusCounts(EmployeeLeave::class, $employeeId),
            'monthly_schedule' => $this->getStatusCounts(EmployeeMonthlySchedule::class, $employeeId),
            'time_adjustment' => $this->getStatusCounts(EmployeeTimeAdjustment::class, $employeeId),
            'overtime' => $this->getStatusCounts(EmployeeOvertime::class, $employeeId),
            'undertime' => $this->getStatusCounts(EmployeeUndertime::class, $employeeId),
            'wfh' => $this->getStatusCounts(EmployeeWfh::class, $employeeId),
            'change_schedule' => $this->getStatusCounts(EmployeeChangeSchedule::class, $employeeId),
            'ob' => $this->getStatusCounts(EmployeeOb::class, $employeeId),
            'offset_earning' => $this->getStatusCounts(EmployeeOffsetEarning::class, $employeeId),
            'offset_availment' => $this->getStatusCounts(EmployeeOffset::class, $employeeId),
        ];

        return response()->json($data);
    }

    public function validationRequests()
    {
        $user = Auth::user();
        $employeeId = $user->employees->employee_id;
        $rolesWithSystemId3 = $user->roles->filter(function($role) {
            return $role->group && $role->group->system_id === 3;
        });

        // Get dealers for ALL roles with system_id 3
        $dealers = [];

        if ($rolesWithSystemId3->isNotEmpty()) {
            $roleIds = $rolesWithSystemId3->pluck('id')->toArray();
            
            $dealers = RoleCompanyAccess::whereIn('role_id', $roleIds)
                ->pluck('dealership_id')
                ->unique()
                ->toArray();
        }

        $timelogEdit = TimelogEdit::with(['employee','requested_by'])
            ->whereIn('dealership_id', $dealers)
            ->selectRaw('
                COUNT(CASE WHEN approved = 0 THEN 1 END) AS count_for_validation
            ')
            ->first()
            ->toArray();

        $data = [
            'leave' => $this->getForValidationCounts(EmployeeLeave::class, $employeeId, $dealers),
            'monthly_schedule' => $this->getForValidationCounts(EmployeeMonthlySchedule::class, $employeeId, $dealers),
            'time_adjustment' => $this->getForValidationCounts(EmployeeTimeAdjustment::class, $employeeId, $dealers),
            'overtime' => $this->getForValidationCounts(EmployeeOvertime::class, $employeeId, $dealers),
            'undertime' => $this->getForValidationCounts(EmployeeUndertime::class, $employeeId, $dealers),
            'wfh' => $this->getForValidationCounts(EmployeeWfh::class, $employeeId, $dealers),
            'change_schedule' => $this->getForValidationCounts(EmployeeChangeSchedule::class, $employeeId, $dealers),
            'ob' => $this->getForValidationCounts(EmployeeOb::class, $employeeId, $dealers),
            'offset_earning' => $this->getForValidationCounts(EmployeeOffsetEarning::class, $employeeId, $dealers),
            'offset_availment' => $this->getForValidationCounts(EmployeeOffset::class, $employeeId, $dealers),
            'timelog_edit' => $timelogEdit,
        ];

        return response()->json($data);
    }

    private function getStatusCounts($model, $employeeId)
    {
        return $model::where('enabled', 1)
            ->where(function ($query) use ($employeeId) {
                $query->where('recommending_id', $employeeId)
                    ->orWhere('approver_id', $employeeId);
            })
            ->selectRaw('
                COUNT(CASE WHEN status = 0 AND recommending_id = ? THEN 1 END) AS pending,
                COUNT(CASE WHEN status = 1 AND approver_id = ? THEN 1 END) AS for_approval,
                COUNT(CASE WHEN status = 2 AND (recommending_id = ? OR approver_id = ?) THEN 1 END) AS approved,
                COUNT(CASE WHEN status = 99 AND (recommending_id = ? OR approver_id = ?) THEN 1 END) AS denied
            ', [$employeeId, $employeeId, $employeeId, $employeeId, $employeeId, $employeeId])
            ->first()
            ->toArray();
    }

    private function getForValidationCounts($model, $employeeId, $dealers)
    {
        return $model::whereHas('employee', function ($query) use ($dealers) {
                $query->where('enabled', 1)
                    ->whereIn('dealer_id', $dealers);
            })
            ->selectRaw('
                COUNT(CASE WHEN status = 2 AND validated = 0 THEN 1 END) AS count_for_validation
            ')
            ->first()
            ->toArray();
    }
}

?>