<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use App\Models\FormUpCountry;
use App\Models\FormEntertaimentPresentation;
use App\Models\FormVehicleRunningCost;
use App\Models\FormMeetingSeminar;
use App\Models\FormOthers;
use App\Models\UserHasCabang;


class DashboardController extends Controller
{
    public function index()
    {
        $role = auth()->user()->getRoleNames()[0];
        $forms = [
            'vehicle' => FormVehicleRunningCost::query(),
            'upcountry' => FormUpCountry::query(),
            'entertainment' => FormEntertaimentPresentation::query(),
            'meeting' => FormMeetingSeminar::query(),
            'others' => FormOthers::query(),
        ];

        if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
            $region_id = auth()->user()->getMyCabangAndRegionId()['region'];

            if ($region_id) {
                $users = UserHasCabang::whereHas('cabang', function ($query) use ($region_id) {
                    $query->where('region_id', $region_id);
                })->pluck('user_id');

                foreach ($forms as $key => $query) {
                    $forms[$key] = $query->whereIn('user_id', $users)->whereIn('status', ['Approved', 'Closed']);
                }
            }
        } elseif ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

            if ($cabang_id) {
                $users = UserHasCabang::where('cabang_id', $cabang_id)->pluck('user_id');

                foreach ($forms as $key => $query) {
                    $forms[$key] = $query->whereIn('user_id', $users)->whereIn('status', ['Approved', 'Closed']);
                }
            }
        } elseif ($role == 'Medical Representatif') {
            foreach ($forms as $key => $query) {
                $forms[$key] = $query->where('user_id', auth()->user()->id)->whereIn('status', ['Approved', 'Closed']);
            }
        } else {
            foreach ($forms as $key => $query) {
                $forms[$key] = $query->whereIn('status', ['Approved', 'Closed']);
            }
        }

        // Sum the filtered queries
        foreach ($forms as $key => $query) {
            $forms[$key] = $query->sum('approved_total');
        }

        return view(
            'backend.pages.dashboard.index',
            [
                'forms' => $forms,
            ]
        );
    }
}
