<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\AuditTrail;
use App\Models\FormUpCountry;
use App\Models\FormEntertaimentPresentation;
use App\Models\FormMeetingSeminar;
use App\Models\FormVehicleRunningCost;
use App\Models\FormOthers;
use App\Models\UserHasCabang;
use Illuminate\Support\Facades\DB;
use App\Models\Cabang;
use App\Models\Region;
use App\Helpers\FormHelper;
use App\Helpers\BudgetHelper;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;

class ReportController extends Controller
{   
    public function upcountry()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        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);
                })->get();

                $userIds = $users->pluck('user_id')->toArray();

                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormUpCountry::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

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

                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormUpCountry::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Medical Representatif') {
            $userId = auth()->user()->id;

            $cabangs = null;
            $regions = null;
            $forms = FormUpCountry::where('user_id', $userId)->get();
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormUpCountry::all();
        }

        // get all params in url
        $params = request()->all();
        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by date range
            if (isset($params['start_date']) || isset($params['end_date'])) {
                $startDate = $params['start_date'] ?? null;
                $endDate = $params['end_date'] ?? null;

                if ($startDate && $endDate) {
                    $forms = $forms->whereBetween('tanggal', [$startDate, $endDate]);
                } elseif ($startDate) {
                    $forms = $forms->where('tanggal', '>=', $startDate);
                } elseif ($endDate) {
                    $forms = $forms->where('tanggal', '<=', $endDate);
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = $forms->where('status', $params['status']);
            }
        }


        return view('backend.pages.report.upcountry', [
            'pageInfo' => [
                'title' => 'Generate Reports For Form Up Country',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions
        ]);
    }

    public function vehicle()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        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);
                })->get();

                $userIds = $users->pluck('user_id')->toArray();

                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormVehicleRunningCost::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

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

                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormVehicleRunningCost::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Medical Representatif') {
            $userId = auth()->user()->id;

            $cabangs = null;
            $regions = null;
            $forms = FormVehicleRunningCost::where('user_id', $userId)->get();
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormVehicleRunningCost::all();
        }

        // get all params in url
        $params = request()->all();

        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by date range
            if (isset($params['start_date']) || isset($params['end_date'])) {
                $startDate = $params['start_date'] ?? null;
                $endDate = $params['end_date'] ?? null;

                if ($startDate && $endDate) {
                    $forms = $forms->whereBetween('tanggal', [$startDate, $endDate]);
                } elseif ($startDate) {
                    $forms = $forms->where('tanggal', '>=', $startDate);
                } elseif ($endDate) {
                    $forms = $forms->where('tanggal', '<=', $endDate);
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = $forms->where('status', $params['status']);
            }
        }

        return view('backend.pages.report.vehicle', [
            'pageInfo' => [
                'title' => 'Generate Reports For Form Vehicle Running Cost',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions
        ]);
    }

    public function entertainment()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        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);
                })->get();

                $userIds = $users->pluck('user_id')->toArray();

                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormEntertaimentPresentation::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

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

                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormEntertaimentPresentation::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Medical Representatif') {
            $userId = auth()->user()->id;

            $cabangs = null;
            $regions = null;
            $forms = FormEntertaimentPresentation::where('user_id', $userId)->get();
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormEntertaimentPresentation::all();
        }

        // get all params in url
        $params = request()->all();

        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by date range
            if (isset($params['start_date']) || isset($params['end_date'])) {
                $startDate = $params['start_date'] ?? null;
                $endDate = $params['end_date'] ?? null;

                if ($startDate && $endDate) {
                    $forms = $forms->whereBetween('tanggal', [$startDate, $endDate]);
                } elseif ($startDate) {
                    $forms = $forms->where('tanggal', '>=', $startDate);
                } elseif ($endDate) {
                    $forms = $forms->where('tanggal', '<=', $endDate);
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = $forms->where('status', $params['status']);
            }
        }

        return view('backend.pages.report.entertainment', [
            'pageInfo' => [
                'title' => 'Generate Reports For Form Entertainment & Presentation',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions
        ]);
    }

    public function meeting()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        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);
                })->get();

                $userIds = $users->pluck('user_id')->toArray();

                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormMeetingSeminar::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

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

                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormMeetingSeminar::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Medical Representatif') {
            $userId = auth()->user()->id;

            $cabangs = null;
            $regions = null;
            $forms = FormMeetingSeminar::where('user_id', $userId)->get();
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormMeetingSeminar::all();
        }

        // get all params in url
        $params = request()->all();

        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by date range
            if (isset($params['start_date']) || isset($params['end_date'])) {
                $startDate = $params['start_date'] ?? null;
                $endDate = $params['end_date'] ?? null;

                if ($startDate && $endDate) {
                    $forms = $forms->whereBetween('tanggal', [$startDate, $endDate]);
                } elseif ($startDate) {
                    $forms = $forms->where('tanggal', '>=', $startDate);
                } elseif ($endDate) {
                    $forms = $forms->where('tanggal', '<=', $endDate);
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = $forms->where('status', $params['status']);
            }
        }

        return view('backend.pages.report.meeting', [
            'pageInfo' => [
                'title' => 'Generate Reports For Form Meeting & Seminar',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions
        ]);
    }

    public function others()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        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);
                })->get();

                $userIds = $users->pluck('user_id')->toArray();

                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormOthers::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Area Manager Cabang') {
            $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];

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

                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormOthers::whereIn('user_id', $userIds)->get();
            }
        } else if ($role == 'Medical Representatif') {
            $userId = auth()->user()->id;

            $cabangs = null;
            $regions = null;
            $forms = FormOthers::where('user_id', $userId)->get();
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormOthers::all();
        }

        // get all params in url
        $params = request()->all();

        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by date range
            if (isset($params['start_date']) || isset($params['end_date'])) {
                $startDate = $params['start_date'] ?? null;
                $endDate = $params['end_date'] ?? null;

                if ($startDate && $endDate) {
                    $forms = $forms->whereBetween('tanggal', [$startDate, $endDate]);
                } elseif ($startDate) {
                    $forms = $forms->where('tanggal', '>=', $startDate);
                } elseif ($endDate) {
                    $forms = $forms->where('tanggal', '<=', $endDate);
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = $forms->where('status', $params['status']);
            }
        }

        return view('backend.pages.report.others', [
            'pageInfo' => [
                'title' => 'Generate Reports For Form Others',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions
        ]);
    }

    public function all()
    {
        $role = auth()->user()->getRoleNames()[0];
        $cabangs = [];
        $regions = [];
        $forms = null;

        $availableBudget = 0;

        $month = date('F');
        $year = date('Y');

        $region_id = auth()->user()->getMyCabangAndRegionId()['region'] ?? null;
        $cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'] ?? null;
        $userId = auth()->user()->id;

        if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
            if ($region_id) {
                $users = UserHasCabang::whereHas('cabang', function ($query) use ($region_id) {
                    $query->where('region_id', $region_id);
                })->get();
                $userIds = $users->pluck('user_id')->toArray();
                $cabangs = Cabang::where('region_id', $region_id)->get();
                $regions = Region::where('id', $region_id)->get();
                $forms = FormHelper::getFormsByUserIds($userIds, $month, $year)->sortByDesc('created_at');
            }
        } elseif ($role == 'Area Manager Cabang') {
            if ($cabang_id) {
                $users = UserHasCabang::where('cabang_id', $cabang_id)->get();
                $userIds = $users->pluck('user_id')->toArray();
                $cabangs = Cabang::where('id', $cabang_id)->get();
                $regions = Region::where('id', $cabangs[0]->region_id)->get();
                $forms = FormHelper::getFormsByUserIds($userIds, $month, $year)->sortByDesc('created_at');
            }
        } elseif ($role == 'Medical Representatif') {
            $cabangs = null;
            $regions = null;
            $forms = FormHelper::getFormsByUserIds([$userId], $month, $year)->sortByDesc('created_at');
        } else {
            $cabangs = Cabang::all();
            $regions = Region::all();
            $forms = FormHelper::getAllForms($month, $year)->sortByDesc('created_at');
        }

        // get all params in url
        $params = request()->all();

        if ($params) {
            // Filter by region
            if (isset($params['region'])) {
                $region = Region::where('code', $params['region'])->first();
                if ($region) {
                    $userIds = UserHasCabang::whereIn('cabang_id', Cabang::where('region_id', $region->id)->pluck('id'))->pluck('user_id')->toArray();
                    $forms = $forms->whereIn('user_id', $userIds);
                }
            }

            // Filter by cabang
            if (isset($params['cabang'])) {
                $cabang = Cabang::where('code', $params['cabang'])->first();
                if ($cabang) {
                    $userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id')->toArray();
                    $forms = isset($forms) ? $forms->whereIn('user_id', $userIds) : FormHelper::getFormsByUserIds($userIds); // Ensure $forms is updated
                    $availableBudget = BudgetHelper::getAvailableBudget($cabang->id);
                }
            }

            // Filter by date range
            if (isset($params['month']) || isset($params['year'])) {
                $month = $params['month'] ?? date('F');
                $year = $params['year'] ?? date('Y');

                $startOfMonth = Carbon::parse("first day of $month $year")->startOfDay();
                $endOfMonth = Carbon::parse("last day of $month $year")->endOfDay();

                if (isset($forms)) {
                    // Determine the date column to filter by
                    $dateColumn = Schema::hasColumn('forms', 'tanggal') ? 'tanggal' : 'created_at';

                    // Further filter existing forms by the determined date column
                    $forms = $forms->whereBetween($dateColumn, [$startOfMonth, $endOfMonth]);
                } else {
                    // Rebuild $forms using FormHelper and filter by role
                    if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
                        if ($region_id) {
                            $users = UserHasCabang::whereHas('cabang', function ($query) use ($region_id) {
                                $query->where('region_id', $region_id);
                            })->get();
                            $userIds = $users->pluck('user_id')->toArray();
                            $cabangs = Cabang::where('region_id', $region_id)->get();
                            $regions = Region::where('id', $region_id)->get();
                            $forms = FormHelper::getFormsByUserIds($userIds, $month, $year)->sortByDesc('tanggal')->sortByDesc('created_at');
                        }
                    } elseif ($role == 'Area Manager Cabang') {
                        if ($cabang_id) {
                            $users = UserHasCabang::where('cabang_id', $cabang_id)->get();
                            $userIds = $users->pluck('user_id')->toArray();
                            $cabangs = Cabang::where('id', $cabang_id)->get();
                            $regions = Region::where('id', $cabangs[0]->region_id)->get();
                            $forms = FormHelper::getFormsByUserIds($userIds, $month, $year)->sortByDesc('tanggal')->sortByDesc('created_at');
                        }
                    } elseif ($role == 'Medical Representatif') {
                        $cabangs = null;
                        $regions = null;
                        $forms = FormHelper::getFormsByUserIds([$userId], $month, $year)->sortByDesc('tanggal')->sortByDesc('created_at');
                    } else {
                        $cabangs = Cabang::all();
                        $regions = Region::all();
                        $forms = FormHelper::getAllForms($month, $year)->sortByDesc('tanggal')->sortByDesc('created_at');
                    }
                }
            }

            // Filter by status
            if (isset($params['status'])) {
                $forms = isset($forms) ? $forms->where('status', $params['status']) : $forms;
            }
        }

        return view('backend.pages.report.all', [
            'pageInfo' => [
                'title' => 'Generate Reports For All Forms',
            ],
            'forms' => $forms,
            'cabang' => $cabangs,
            'regions' => $regions,
            'availableBudget' => $availableBudget
        ]);
    }
}
