<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Resource;
use Illuminate\Http\Response;
use App\Builders\ChartBuilder;
use App\Services\ModuleService;
use App\Services\ReportService;
use App\Builders\ChartDrillBuilder;
use Illuminate\Support\Facades\Auth;
use App\Repositories\ChartRepository;
use App\Services\ChartDetailsService;
use Illuminate\Pagination\LengthAwarePaginator;

class ChartService
{
    public $groupService;
    public $chartBuilder;
    public $reportService;
    public $moduleService;
    public $chartRepository;
    public $categoryService;
    public $chartDrillService;
    public $chartDetailsService;
    public $dataConnectionService;
    public $dataConnectionTablesService;
    public function __construct(
        ReportService $reportService,
        ChartRepository $chartRepository,
        CategoryService $categoryService,
        ChartBuilder $chartBuilder,
        GroupService $groupService,
        ChartDrillService $chartDrillService,
        ChartDetailsService $chartDetailsService,
        DataConnectionService $dataConnectionService,
        DataConnectionTablesService $dataConnectionTablesService,
        ModuleService $moduleService
    ) {
        $this->reportService               = $reportService;
        $this->chartRepository             = $chartRepository;
        $this->chartBuilder                = $chartBuilder;
        $this->categoryService             = $categoryService;
        $this->groupService                = $groupService;
        $this->chartDrillService           = $chartDrillService;
        $this->chartDetailsService         = $chartDetailsService;
        $this->dataConnectionService       = $dataConnectionService;
        $this->dataConnectionTablesService = $dataConnectionTablesService;
        $this->moduleService               = $moduleService;

    }

    public function index($request)
    {
        $charts              = $this->getCharts($request)->get();
        $defaultChartPerPage = config('srm_config.dashboard.charts_per_page', 6);
        $currentPage         = LengthAwarePaginator::resolveCurrentPage();

        $currentPageCharts = $charts->slice(($currentPage - 1) * $defaultChartPerPage, $defaultChartPerPage);

        if ($currentPage == 1) {
            $firstChart = $currentPageCharts->slice(0, 1)->first();

            $currentPageCharts = $currentPageCharts->slice(1, count($currentPageCharts));

        }

        $sortedCharts = $this->sortCharts($currentPageCharts);

        if ($currentPage == 1) {
            $sortedCharts->prepend($firstChart);
        }

        return new LengthAwarePaginator(
            $sortedCharts,
            count($charts),
            $defaultChartPerPage,
            $currentPage,
            [
                'path'     => LengthAwarePaginator::resolveCurrentPath(),
                'pageName' => 'page'
            ]
        );
    }

    public function show($chart)
    {
        $chart = Resource::findResourceByName($chart)->firstOrFail();
        $this->checkChartAccessPermission($chart);

        (new ChartBuilder($chart))->build();
        return $chart;

    }

    public function buildChart(Resource $chart)
    {
        $this->checkChartAccessPermission($chart);

        (new ChartBuilder($chart))->build();

        $this->chartDetailsService->prepareDetails($chart);
        return $chart;

    }

    public function details(Resource $chart)
    {
        $this->checkChartAccessPermission($chart);
        $this->checkChartDetails($chart);

        (new ChartBuilder($chart))->build();

        $this->chartDetailsService->prepareDetails($chart);
        return $chart;

    }

    public function autoExport(Resource $chart)
    {
        // $this->checkChartAccessPermission($chart);
        $this->checkChartDetails($chart);

        (new ChartBuilder($chart))->build();

        $this->chartDetailsService->prepareDetails($chart);
        return $chart;

    }

    private function prepareChartDetails(Resource $chart)
    {
        $dateRange     = $chart->getResourceConfiguration('date_range');
        $timeScale     = $chart->getResourceConfiguration('date_time_scale');
        $xAxis         = $chart->data["x_axis"];
        $drillBuilder  = new ChartDrillBuilder($chart);
        $preparedXAxis = [];

        if (empty($dateRange) || empty($timeScale)) {
            return;
        }

        if (in_array($dateRange, ["this_year", "last_12_months"]) && strtolower($timeScale) == "quarters") {

            foreach ($xAxis as $value) {
                $dateValue       = Carbon::parse($value)->addMonths(2)->lastOfMonth()->toDateString();
                $preparedXAxis[] = "{$value} - {$dateValue}";
            }

        }

        if (in_array($dateRange, ["this_month", "last_30_days"]) && strtolower($timeScale) == "weeks") {

            foreach ($xAxis as $value) {
                $value = Carbon::parse($value);

                $dateValue = $drillBuilder->populateOptions()->handleWeeks($value);

                $preparedXAxis[] = "{$dateValue[0]} - {$dateValue[1]}";
            }

        }

        $chart->data = ["x_axis" => $preparedXAxis, "y_axis" => $chart->data["y_axis"]];
    }

    public function detailsExport(Resource $chart)
    {
        $this->checkChartAccessPermission($chart);
        $this->checkChartDetails($chart);

        (new ChartBuilder($chart))->build();
        $this->chartDetailsService->prepareDetails($chart);

        return $chart;

    }

    public function drill(Resource $chart, $xValue)
    {

        $this->checkChartAccessPermission($chart);

        return $this->chartDrillService->getData($chart, $xValue);
    }

    public function drillExport(Resource $chart, $xValue)
    {

        if (is_null($xValue)) {
            abort(Response::HTTP_NOT_FOUND);
        }

        $this->checkChartAccessPermission($chart);

        return $this->chartDrillService->getData($chart, $xValue);
    }

    public function edit(Resource $chart)
    {

        // $this->checkThereIsGroupsAndCategories();

        $this->checkChartCreatorPermission($chart);

        $types = ["date", "datetime", "char", "varchar", "string", "timestamp"];

        $connection = $chart->getConnectionAsString();

        $chartsTypes = $this->chartTypes();

        $categories = $this->categoryService->getCategories();

        $connections = $this->dataConnectionService->getAllConnections();

        $groups = auth()->user()->isAdminOrOwner() ? $this->groupService->getAllGroups() : [auth()->user()->group];

        $tables = $this->dataConnectionTablesService->getTables($connection);

        $xTableColumns = $chart->getResourceConfiguration('chart_type') == "timeseries"
        ? $this->dataConnectionTablesService->getDateTimeColumns(
            $connection,
            $chart->getResourceConfiguration('x_table'),
            $types
        )
        : $this->dataConnectionTablesService->getColumns(
            $connection,
            $chart->getResourceConfiguration('x_table')
        );

        $yTableColumns = $this->dataConnectionTablesService->getColumns(
            $connection,
            $chart->getResourceConfiguration('y_table')
        );

        $xColumnType = $this->dataConnectionTablesService->getColumnType(
            $connection,
            $chart->getResourceConfiguration('x_table'),
            $chart->getResourceConfiguration('x_axis_column')
        );

        $dateRanges = $this->dateRanges();
        $timeScales = $this->timeScales();

        $textualCount = $this->getTextualCount(
            $connection,
            $chart->getResourceConfiguration('x_table'),
            $chart->getResourceConfiguration('x_axis_column')
        );

        $dataFilterItems = $this->dataConnectionTablesService->getValues(
            $connection,
            $chart->getResourceConfiguration('x_table'),
            $chart->getResourceConfiguration('x_axis_column')
        );

        return [
            $chartsTypes,
            $chart,
            $categories,
            $connections,
            $groups,
            $tables,
            $xTableColumns,
            $yTableColumns,
            $xColumnType,
            $dateRanges,
            $timeScales,
            $textualCount,
            $dataFilterItems
        ];

    }

    public function destroy($chart)
    {
        $this->checkChartCreatorPermission($chart);

        $chart->homeWidgets()->delete();
        $chart->dashboardWidgets()->delete();

        $chart->delete();
    }

    public function getAllCharts($request)
    {
        return Resource::when(
            (isset($request->chartName)),
            function ($q) use ($request) {
                $q->where('name', 'LIKE', '%' . $request->chartName . '%');

            }
        )->when(isset($request->chartTitle), function ($q) use ($request) {
            $q->whereHas('configurations', function ($q) use ($request) {
                return $q->where('Json_configurations->title', 'LIKE', '%' . $request->chartTitle . '%');
            });

        })->when(isset($request->chartType), function ($q) use ($request) {
            $q->whereHas('configurations', function ($q) use ($request) {
                return $q->where('chart_type', $request->chartType);
            });

        })->whereHas('module', function ($q) {

            return $q->where('name', 'Charts');
        })->orWhereHas('module.parent', function ($q) {
            return $q->where('name', 'Charts');
        })
            ->with('category')
            ->orderBy('created_at', 'desc');
    }

    public function getRecentChart()
    {
        return Resource::whereHas('module', function ($q) {

            return $q->where('name', 'Charts');
        })->orWhereHas('module.parent', function ($q) {
            return $q->where('name', 'Charts');
        })
            ->with('category')
            ->orderBy('created_at', 'desc')
            ->first();
    }

    public function getAuthedUserCharts($request)
    {
        $prefix = config("srm_config.installer.table_prefix", "srm_");

        return Resource::when(
            (isset($request->chartName)),
            function ($q) use ($request) {
                $q->where('name', 'LIKE', '%' . $request->chartName . '%');

            }
        )->when(isset($request->chartTitle), function ($q) use ($request) {
            $q->whereHas('configurations', function ($q) use ($request) {
                return $q->where('Json_configurations->title', 'LIKE', '%' . $request->chartTitle . '%');
            });

        })->when(isset($request->chartType), function ($q) use ($request) {
            $q->whereHas('configurations', function ($q) use ($request) {
                return $q->where('chart_type', $request->chartType);
            });

        })->where(function ($q) use ($prefix) {
            $q->where(function ($q) {
                $q->whereHas('module', function ($q) {
                    return $q->where('name', 'Charts');
                })->orWhereHas('module.parent', function ($q) {
                    return $q->where('name', 'Charts');
                });
            })->where(function ($q) use ($prefix) {
                $q->whereHas('resource_permissions', function ($q) use ($prefix) {
                    return $q->where($prefix . 'resource_permissions.group_id', auth()->user()->group_id);
                })->orWhere(function ($q) {
                    $q->where('access_control_type', 'Public');
                });
                // ->orWhere('resource_creator', auth()->id());
            });
        })
            ->with('category')
            ->orderBy('created_at', 'desc');
    }

    public function showChartTypeStep()
    {
        $this->checkCanUserCreateChart();
        // $this->checkThereIsGroupsAndCategories();
    }

    private function checkCanUserCreateChart()
    {

        if (
            !$this->moduleService->checkCurrentUserGroupCanCreateModule('Charts')
            && !auth()->user()->isAdminOrOwner()
        ) {
            abort(403, trans('charts.messages.permission_denied'));
        }

    }

    public function chartTypes()
    {
        return [
            ["image" => "bar-chart.png", "label" => "Bar Chart", "value" => "bar-chart"],
            ["image" => "hor bar.png", "label" => "Horizontal Bar", "value" => "horizontal-chart"],
            // ["image" => "3d bar-chart.png" , "label" => "3D Bar Chart", "value" => "3d-bar-chart"],
            ["image" => "line-chart.png", "label" => "Line Chart", "value" => "line-chart"],
            ["image" => "timeserice.png", "label" => "Timeseries", "value" => "timeseries"],
            ["image" => "spline.png", "label" => "Spline Chart", "value" => "spline-chart"],
            ["image" => "pie-chart.png", "label" => "Pie Chart", "value" => "pie-chart"],
            // ["image" => "3d pie-chart.png" , "label" => "3D Pie Chart", "value" => "3d-pie-chart"],
            ["image" => "dount chart.png", "label" => "Donut Chart", "value" => "donut-chart"],
            // ["image" => "3d dount.png" , "label" => "3D Donut Chart", "value" => "3d-donut-chart"],
            ["image" => "scatter.png", "label" => "Scatter Chart", "value" => "scatter-chart"],
            ["image" => "area.png", "label" => "Area Chart", "value" => "area-chart"]
        ];
    }

    public function dateRanges()
    {
        return [
            ["label" => "This Year and The 5 Previous Years", "value" => "last_5_years"],
            ["label" => "This Year", "value" => "this_year"],
            ["label" => "Last 12 Months", "value" => "last_12_months"],
            ["label" => "This Month and The 5 Previous Months", "value" => "this_6_months"],
            ["label" => "Last 6 Months", "value" => "last_6_months"],
            ["label" => "This Month and The 2 Months Before", "value" => "this_3_months"],
            ["label" => "Last 3 Months", "value" => "last_3_months"],
            ["label" => "This Month", "value" => "this_month"],
            ["label" => "Last 30 Days", "value" => "last_30_days"],
            ["label" => "This Week", "value" => "this_week"],
            ["label" => "Last 7 Days", "value" => "last_7_days"],
            ["label" => "Today", "value" => "today"],
            ["label" => "Yesterday", "value" => "yesterday"]
        ];
    }

    public function timeScales()
    {
        return [
            ["label" => "Hours", "value" => "hours"],
            ["label" => "Days", "value" => "days"],
            ["label" => "Weeks", "value" => "weeks"],
            ["label" => "Months", "value" => "months"],
            ["label" => "Quarters", "value" => "quarters"],
            ["label" => "Years", "value" => "years"]
        ];
    }

    public function getTextualCount($connection, $table, $column)
    {
        return $this->dataConnectionService->getConnection($connection)->table($table)
            ->whereRaw("{$column} NOT REGEXP '^[0-9]+$'")
            ->whereNotNull($column)
            ->count();
    }

    public function storeApperanceStep($request)
    {
        $sectionsColorPalette = in_array($request->validated('chart_type'), ['pie-chart', 'donut-chart']) ? $request->validated('sections_color_palette') : null;

        if (!is_null(session()->get('chart_session_wizard_configuration'))) {

            session()->put('chart_session_wizard_configuration', [
                'chart_type'             => !is_null($request->validated('chart_type')) ? $request->validated('chart_type') : $session["chart_type"],
                'widget_size'            => !is_null($request->validated('widget_size')) ? $request->validated('widget_size') : $session["widget_size"],
                'map_selection'          => $request->has('map_selection') ? $request->validated('map_selection') : "",
                'sections_color_palette' => $sectionsColorPalette
            ] + session()->get('chart_session_wizard_configuration'));

        } else {
            session()->put('chart_session_wizard_configuration', [
                'chart_type'             => !is_null($request->validated('chart_type')) ? $request->validated('chart_type') : $session["chart_type"],
                'widget_size'            => !is_null($request->validated('widget_size')) ? $request->validated('widget_size') : $session["widget_size"],
                'map_selection'          => $request->has('map_selection') ? $request->validated('map_selection') : "",
                'sections_color_palette' => $sectionsColorPalette
            ]);

        }

    }

    public function storeSettingStep($request)
    {
        session()->put('chart_session_wizard_configuration', [
            'name'          => $request->validated('name'),
            'title'         => $request->validated('title'),
            'category'      => $request->validated('category'),
            'connection'    => $request->validated('connection'),
            'security_type' => $request->validated('security_type'),
            'groups'        => $request->has('groups') && $request->validated('security_type') == "private" ? $request->validated('groups') : null,
            'chart_link'    => $request->has('chart_link') ? true : false
        ] + session()->get('chart_session_wizard_configuration'));
    }

    public function updateSettingStep($request, $chart)
    {
        session()->put('chart_session_wizard_configuration', [
            'name'          => $request->validated('name'),
            'title'         => $request->validated('title'),
            'category'      => $request->validated('category'),
            'connection'    => $chart->data_connection_id,
            'security_type' => $request->validated('security_type'),
            'groups'        => $request->has('groups') && $request->validated('security_type') == "private" ? $request->validated('groups') : null,
            'chart_link'    => $request->has('chart_link') ? true : false
        ] + session()->get('chart_session_wizard_configuration'));
    }

    public function storeDataStep($request)
    {
        session()->put('chart_session_wizard_configuration', [
            'x_table'             => $request->validated('x_table'),
            'x_axis_column'       => $request->validated('x_axis_column'),
            'date_range'          => $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column')) ? $request->validated('date_range') : "",
            'date_time_scale'     => $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column')) ? $request->validated('date_time_scale') : "",
            'data_filter_columns' => $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column')) ? null : $request->validated('data_filter_columns'),
            'y_table'             => $request->validated('y_table'),
            'y_axis_column'       => $request->validated('y_axis_column'),
            'label'               => $request->validated('label'),
            'function'            => $request->validated('function'),
            'drill_down'          => !is_null($request->validated('drill_down')) ? true : false,
            'drill_down_columns'  => !is_null($request->validated('drill_down_columns')) ? $request->validated('drill_down_columns') : ""
        ] + session()->get('chart_session_wizard_configuration'));

        $this->chartRepository->store();
    }

    public function updateDataStep($request, $chart)
    {

        if (!is_null(session()->get('chart_session_wizard_configuration'))) {
            session()->put('chart_session_wizard_configuration', [
                'x_table'             => $request->validated('x_table'),
                'x_axis_column'       => $request->validated('x_axis_column'),
                'date_range'          => (
                    $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart)
                    || session()->get('chart_session_wizard_configuration')["chart_type"] == "timeseries"
                ) ? $request->validated('date_range') : "",
                'date_time_scale'     => (
                    $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart)
                    || session()->get('chart_session_wizard_configuration')["chart_type"] == "timeseries"
                ) ? $request->validated('date_time_scale') : "",
                'data_filter_columns' => $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart) ? null : $request->validated('data_filter_columns'),
                'y_table'             => $request->validated('y_table'),
                'y_axis_column'       => $request->validated('y_axis_column'),
                'label'               => $request->validated('label'),
                'function'            => $request->validated('function'),
                'drill_down'          => !is_null($request->validated('drill_down')) ? true : "",
                'drill_down_columns'  => !is_null($request->validated('drill_down_columns')) ? $request->validated('drill_down_columns') : ""
            ] + session()->get('chart_session_wizard_configuration'));
        } else {
            session()->put('chart_session_wizard_configuration', [
                'x_table'             => $request->validated('x_table'),
                'x_axis_column'       => $request->validated('x_axis_column'),
                'date_range'          => (
                    $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart)
                    || $chart->configurations->chart_type == "timeseries"
                ) ? $request->validated('date_range') : "",
                'date_time_scale'     => (
                    $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart)
                    || $chart->configurations->chart_type == "timeseries"
                ) ? $request->validated('date_time_scale') : "",
                'data_filter_columns' => $this->isColumnDate($request->validated('x_table'), $request->validated('x_axis_column'), false, $chart) ? null : $request->validated('data_filter_columns'),
                'y_table'             => $request->validated('y_table'),
                'y_axis_column'       => $request->validated('y_axis_column'),
                'label'               => $request->validated('label'),
                'function'            => $request->validated('function'),
                'drill_down'          => !is_null($request->validated('drill_down')) ? true : "",
                'drill_down_columns'  => !is_null($request->validated('drill_down_columns')) ? $request->validated('drill_down_columns') : ""
            ]);
        }

        $this->chartRepository->update($chart);
    }

    public function getDateRangeTimeScale($dateRange)
    {

        switch ($dateRange) {
            case 'last_5_years':
                return ["years"];
                break;
            case 'this_year':
            case 'last_12_months':
                return ["quarters", "months"];
                break;
            case 'this_6_months':
            case 'last_6_months':
            case 'this_3_months':
            case 'last_3_months':
                return ["months"];
                break;
            case 'this_month':
            case 'last_30_days':
                return ["days", "weeks"];
                break;
            case 'this_week':
            case 'last_7_days':
                return ["days"];
                break;
            case 'today':
            case 'yesterday':
                return ["hours"];
                break;
            default:
                break;
        }

    }

    public function isColumnDate($table, $column, $isSession = true, $chart = null)
    {

        if ($isSession) {
            $connection = session()->get('chart_session_wizard_configuration')["connection"];
        } else {
            $connection = $chart->getConnectionAsString();
        }

        return in_array($this->dataConnectionTablesService->getColumnType($connection, $table, $column), ["timestamp", "date", "datetime"]);

    }

    public function changeChartCategory($chart, $data)
    {

        $this->checkChartCreatorPermission($chart);

        $chart->category_id = $data['chart_category'];
        $chart->save();
    }

    public function formatXValue($chart, $xValue)
    {
        $timeScale = $chart->getResourceConfiguration('date_time_scale');

        if (empty($timeScale)) {
            return $xValue;
        }

        switch ($timeScale) {
            case 'years':
                return Carbon::parse($xValue)->format('Y');
                break;
            case 'quarters':
                $date = explode(' to ', $xValue)[0]; // remove 'to' from $xValue
                $date = Carbon::parse($date);
                return $date->format('Y-m-d') . ' to ' . $date->addMonths(3)->endOfMonth()->format('Y-m-d');
                break;
            case 'months':
                return Carbon::parse($xValue)->format('Y-m');
                break;
            default:
                return $xValue;
                break;
        }

    }

    private function checkChartCreatorPermission(Resource $resource)
    {

        if (
            !(auth()->user()->isAdminOrOwner() ||
                $resource->resource_creator === auth()->user()->user_ID)
        ) {
            abort(403, trans('charts.messages.unauthorized'));
        }

    }

    private function checkChartAccessPermission(Resource $chart)
    {
        $user = auth()->user();

        $isAuthorized = (
            ($user && $user->isAdminOrOwner()) ||
            strtolower($chart->access_control_type) == "public" ||
            // ($user && $chart->resource_creator === $user->user_ID) ||
            ($user && in_array($user->group_id, $chart->resource_permissions->pluck("group_ID")->toArray()))
        );

        if (!$isAuthorized) {
            abort(403, trans('charts.messages.unauthorized'));
        }

    }

    private function checkChartDrillAccessPermission(Resource $chart)
    {

        if (
            !(auth()->user()->isAdminOrOwner() || strtolower($chart->access_control_type) == "public" ||
                in_array(auth()->user()->group_id, $chart->resource_permissions->pluck("group_ID")->toArray()))
        ) {
            abort(403, trans('charts.messages.unauthorized'));
        }

    }

    private function checkChartDetails(Resource $chart)
    {

        if (!$chart->getResourceConfiguration('chart_link')) {
            abort(403, trans('charts.messages.no_details'));
        }

    }

    public function checkThereIsGroupsAndCategories()
    {

        if ($this->categoryService->getCategoriesCount() == 0 || $this->groupService->getGroupsCount() == 0) {
            abort(400, trans('charts.messages.create_group_and_category'));
        }

    }

    private function sortCharts($charts)
    {
        $charts = $charts->values();

        if (count($charts) == 1) {

            $adjustedCharts[] = $charts[0];
            return collect($adjustedCharts);
        }

        for ($i = 0; $i < count($charts);) {
            $condition = LengthAwarePaginator::resolveCurrentPage() == 1
            ? count($charts->slice(1, $i)->where('widget_size', Resource::CHART_HALF_SIZE)) % 2 != 0
            : count($charts->slice(1, $i)->where('widget_size', Resource::CHART_HALF_SIZE)) % 2 == 0;

            if (
                isset($charts[$i + 1]) &&
                $charts[$i]['widget_size'] == Resource::CHART_HALF_SIZE &&
                $charts[$i + 1]['widget_size'] == Resource::CHART_FULL_SIZE
                && count($charts->slice(0, $i)->where('widget_size', Resource::CHART_HALF_SIZE)) % 2 == 0
            ) {
                $temp           = $charts[$i + 1];
                $charts[$i + 1] = $charts[$i];
                $charts[$i]     = $temp;
            } else {
                $i++;
            }

        }

        return $charts;

    }

// public function loginAsAdmin()

// {

//     // Retrieve the admin user

//     $admin = User::where('is_admin', true)->first();

//     // Log in as the admin user

//     Auth::login($admin);

//     // Ensure the user is authenticated

//     if (!Auth::check()) {

//         return response()->json(['error' => 'Failed to authenticate as admin'], 401);

//     }

//     // Get the session ID and CSRF token

//     $sessionId = session()->getId();

//     $csrfToken = csrf_token();

//     // Return session details

//     return response()->json([

//         'session_id' => $sessionId,

//         'csrf_token' => $csrfToken

//     ]);
    // }

    public function generateDetailsPdf($request, $chart)
    {

        $url = route('charts.autoexport', $chart->id);

        $securityKey  = config('srm_install_config.security_key');
        $cookieHeader = "X-Internal-Request={$securityKey}";

        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // curl_setopt($ch, CURLOPT_COOKIE, $cookieHeader);

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'X-Internal-Request: ' . $securityKey
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Check for errors
        if (curl_errno($ch)) {
            return response()->json(['error' => curl_error($ch)], 500);
        }

        // Close the cURL session
        curl_close($ch);

        // Return the response
        return response()->json([
            'status'   => $httpCode,
            'response' => json_decode($response, true)
        ]);

    }

    private function getChartByPage()
    {
        return config('srm_config.dashboard.charts_per_page', 6);
    }

    private function getNumberOfPages($request)
    {
        $chartPerPage = $this->getChartByPage();
        return $this->getCharts($request)->paginate($chartPerPage);
    }

    public function getChartLastPage($request)
    {
        return $this->getNumberOfPages($request)->lastPage();
    }

    private function getCharts($request)
    {

        if (auth()->user()->isAdminOrOwner()) {
            return $this->getAllCharts($request);
        } else {
            return $this->getAuthedUserCharts($request);
        }

    }

}
