<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\Province;
use App\Models\User;
use App\Models\InfoItem;
use App\Models\ContractSubItems;
use App\Models\SafetyAndPrivacy;
use App\Models\Accident;
use App\Models\RoadObserved;
use App\Models\ReportSummary as ReportSummaryModel;

class ReportSummary extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'reports:rms-summary';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Prepares and Inserts data from specific reports into `rms_reports_summary` table.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        // initializing
        $from_date_array = explode('-', verta()->startYear()->format('Y-m-d'));
        $from_date = implode('-', verta()->getGregorian($from_date_array[0], $from_date_array[1], $from_date_array[2])) . ' 00:00:00';
        $to_date_array = explode('-', verta()->endYear()->format('Y-m-d'));
        $to_date = implode('-', verta()->getGregorian($to_date_array[0], $to_date_array[1], $to_date_array[2])) . ' 23:59:59';


        // (BEGIN) receipt

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'receipt'],
            [
                'report_name' => 'receipt',
                'data' => [
                    'chart' => Accident::select(DB::raw('sum(sum) as sum'), 'province_fa')->where('status', '5')->groupby('province_id')->orderby('sum', 'desc')->get()->take(5)->toArray(),
                    'sum' => Accident::select(DB::raw('sum(sum) - sum(ojrate_nasb) as sum'))->first('sum'),
                ]
                
                
            ]
        );
        // (END) receipt


        // (BEGIN) safety_and_privacy
        foreach (InfoItem::where('type', "privacy")->get() as $key => $value) {
            $finalArray['label'][] = $value['sub_item_str'];
        }

        for ($step = 1; $step < 4; $step++) {
            $finalArray['data'][] = SafetyAndPrivacy::select(DB::raw('count(*) as count'))->where('step', $step)->groupby('info_id')->get()->map(function ($item) {
                return $item->count;
            })->toArray();
        }

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'safety_and_privacy'],
            [
                'report_name' => 'safety_and_privacy',
                'data' => $finalArray
            ]
        );

        // (END) safety_and_privacy

        // (BEGIN) road_item
        $finalArray = [];

        foreach (InfoItem::where('type', "item")->groupby('item')->get() as $key => $value) {
            $finalArray['label'][$value['item']] = $value['item_str'];
            $finalArray['data'][$value['item']] = 0;
        }
        $data = DB::table('road_items_projects')
                    ->select('item_fa as label', 'item')
                    ->whereBetween('created_at', [$from_date, $to_date])
                    ->get();

        $dataAfter = array();
        foreach ($data as $key => $value) {
            $dataAfter[$value->item]['label'] = $value->label;
            if(!isset($dataAfter[$value->item]['count'])) {
                $dataAfter[$value->item]['count'] = 0;
            }
            $dataAfter[$value->item]['count']++;

        }

        foreach ($dataAfter as $key => $value) {
            $finalArray['label'][$key] = $value['label'];
            $finalArray['data'][$key] = $value['count'];
        }

        $temporary = [];
        foreach ($finalArray['label'] as $value) {
            $temporary['label'][] = $value;
        }

        foreach ($finalArray['data'] as $value) {
            $temporary['data'][] = $value;
        }
        array_multisort($temporary['data'], SORT_DESC, $temporary['label']);

        $myArray = [];

        $myArray['labels'] = $temporary['label'];
        $myArray['datasets'][] = [
            'label' => 'به تفکیک نوع پروژه های راهداری',
            'data' => $temporary['data']
        ];
        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'road_item'],
            [
                'report_name' => 'road_item',
                'data' => $myArray
            ]
        );
        // (END) road_item




        // (BEGIN) gashte roozaneh
        $gasht_rozane = DB::table('road_patrols')
                    ->select(
                        DB::raw('count(road_patrols.id) as count_number'),
                        DB::raw('sum(distance) as distance'),
                        'road_patrols.province_fa'
                    )
                    ->groupBy('road_patrols.province_id')
                    ->orderBy('distance', 'desc')
                    ->limit(5)
                    ->get()->toArray();

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'gasht_rozane'],
            [
                'report_name' => 'gasht_rozane',
                'data' => $gasht_rozane
            ]
        );

        // (END) gashte roozaneh

        // (BEGIN) [POSTERS CONTROLLER => progressInfo] user activity

        // for ($i = 3; $i >= 0; $i--) {

        //     $from_date_array = explode('-', verta()->startYear()->subYear($i)->format('Y-m-d'));
        //     $from_date = implode('-', verta()->getGregorian($from_date_array[0], $from_date_array[1], $from_date_array[2])) . ' 00:00:00';
        //     $to_date_array = explode('-', verta()->subYear($i)->endYear()->format('Y-m-d'));
        //     $to_date = implode('-', verta()->getGregorian($to_date_array[0], $to_date_array[1], $to_date_array[2])) . ' 23:59:59';

        //     $user_activity_sql = "
        //     SELECT SUM(majmoe) AS activity
        //     FROM (
        //         SELECT *, COUNT(quantity) AS majmoe
        //         FROM (
        //             SELECT *,
        //                 COUNT(*) AS quantity
        //             FROM (
        //                 SELECT YEAR (created_at) AS yy,
        //                     MONTH (created_at) AS mm,
        //                     DAY (created_at) AS dd,
        //                     HOUR (created_at) AS hh,
        //                     user_id
        //                 FROM user_activity_logs
        //                 WHERE created_at BETWEEN '{$from_date}' AND '{$to_date}'
        //                 ) user_activity_distinct
        //             GROUP BY yy,
        //                 mm,
        //                 dd,
        //                 hh,
        //                 user_id
        //         ) user_activity_by_hour_and_
        //         GROUP BY user_id
        //     ) AS calculated_table;";

        //     $user_activity = (int) DB::select(DB::raw($user_activity_sql))[0]->activity;
        //     $user_activity_count_sql = "SELECT count(*) as cnt
        //             FROM user_activity_logs WHERE created_at between '{$from_date}' and '{$to_date}'";
        //     $user_activity_count = (int) DB::select(DB::raw($user_activity_count_sql))[0]->cnt;

        //     $array[] = [
        //         'user_activity' => $user_activity,
        //         'user_activity_count' => $user_activity_count,
        //         'year' => ($from_date_array[0] == '1400') ? 'نیمه دوم 1400' : $from_date_array[0]
        //     ];

        // }


        $number_of_past_days = verta()->startYear()->diffDays();

    
        $user_activity_sql = "
            SELECT SUM(majmoe) AS activity 
            FROM (
                SELECT *, COUNT(quantity) AS majmoe
                FROM (
                    SELECT *,
                        COUNT(*) AS quantity
                    FROM (
                        SELECT YEAR (created_at) AS yy,
                            MONTH (created_at) AS mm,
                            DAY (created_at) AS dd,
                            HOUR (created_at) AS hh,
                            user_id
                        FROM user_activity_logs
                        WHERE created_at BETWEEN '{$from_date}' AND '{$to_date}'
                        ) user_activity_distinct
                    GROUP BY yy,
                        mm,
                        dd,
                        hh,
                        user_id
                ) user_activity_by_hour_and_ 
                GROUP BY user_id
            ) AS calculated_table;";

        $user_activity = (int) DB::select(DB::raw($user_activity_sql))[0]->activity;
        // $user_activity_count_sql = "SELECT  COUNT(DISTINCT user_id) AS cnt FROM user_activity_logs ;";
        $user_activity_number = (int) DB::select(DB::raw("SELECT  COUNT(DISTINCT user_id) AS cnt FROM user_activity_logs ;"))[0]->cnt;
        $array[] = [
            'user_count' => User::count(),
            'user_activity_avarage' => round(($user_activity / 143) / $user_activity_number),
            'year' => $from_date_array[0]
        ];
        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'user_activity'],
            [
                'report_name' => 'user_activity',
                'data' => $array,
            ]
        );


        // (END) [POSTERS CONTROLLER => progressInfo] user activity

        // (BEGIN) [BAMA CONTROLLER => homepage_report] tedad proje be tafkik noe va akharin vaziat
        $collection = ContractSubItems::groupBy('project_type_id')
                                      ->select('project_type_id as id', 'project_type_fa as label')
                  ->where('progress_project', '<', 100)
                  ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }

        $data = DB::table('contract_subitems')
                  ->groupBy('project_type_id')
                  ->select('project_type_id as id', 'project_type_fa as label', DB::raw('count(*) as count'))
                  ->where('progress_project', '<', 100)
                  ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }


        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            $finalArray['label'][] = $value;
            $finalArray['data'][] = $array['data'][$index];
        }

        $type_sperate = $finalArray;

        $collection = ContractSubItems::groupBy('last_status_id')
                                    ->where('last_status_id', '!=', '0')
                                    ->where('progress_project', '<', 100)
                                    ->select('last_status_id as id', 'last_status_fa as label')
                                    ->get();
        $array = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->label;
            $array['data'][$value->id] = 0;
        }


        $data = DB::table('contract_subitems')
                ->where('last_status_id', '!=', '0')
                ->where('progress_project', '<', 100)
                ->groupBy('last_status_id')
                ->select('last_status_id as id', 'last_status_fa as label', DB::raw('count(*) as count'))
                ->get();

        foreach ($data as $key => $item) {
            $array['data'][$item->id] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            $finalArray['label'][] = $value;
            $finalArray['data'][] = $array['data'][$index];
        }

        $status_sperate = $finalArray;

        $total_projects_count = ContractSubItems::count();

        $point_data = ContractSubItems::select('id', 'start_lat', 'start_lng', 'project_type_id')
                                    ->where('progress_project', '<', 100)
                                    ->whereBetween('contract_date_from_parent_contract', [$from_date , $to_date])
        ->get();


        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'contract_subitem_projects'],
            [
                'report_name' => 'contract_subitem_projects',
                'data' => [
                    'type_sperate' => $type_sperate,
                    'status_sperate' => $status_sperate,
                    'count' => $total_projects_count,
                    'points' => $point_data,
                ],
            ]
        );
        // (END) [BAMA CONTROLLER => homepage_report] tedad proje be tafkik noe va akharin vaziat

        // (BEGIN) [BI CONTROLLER => percentComplaintsHandled] total percent complaints handled
        $countHandled = RoadObserved::where('rms_status', "<>", 0)
                                    ->count();

        $countAll = RoadObserved::count();

        $total_percent_complaints_handled = $countAll ? round(($countHandled / $countAll) * 100) : 0;

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'total_percent_complaints_handled'],
            [
                'report_name' => 'total_percent_complaints_handled',
                'data' => $total_percent_complaints_handled
            ]
        );

        // (END) [BI CONTROLLER => percentComplaintsHandled] total percent complaints handled


        // (BEGIN) [BI CONTROLLER => separationComplainTypeRahdariComplains]
        $dataLabel = RoadObserved::select('fk_FeatureType as id', 'FeatureTypeTitle as label', DB::raw('count(*) as count'))
                                    ->groupBy('fk_FeatureType')
                                    ->get();

        $array = [];
        foreach ($dataLabel as $value) {
            $array['label'][$value->id] = $value->label;
            $array['dataVasel'][$value->id] = 0;
            $array['dataResidegiShode'][$value->id] = 0;
        }
        $dataResidegiShode = RoadObserved::where('rms_status', '!=', 0)
                                         ->select('fk_FeatureType as id', DB::raw('count(*) as count'))
                                         ->groupBy('fk_FeatureType')
                                         ->get();

        foreach ($dataResidegiShode as $key => $item) {
            $array['dataResidegiShode'][$item->id] = $item->count;
        }

        $dataVasel = RoadObserved::select('fk_FeatureType as id', DB::raw('count(*) as count'))
                                 ->groupBy('fk_FeatureType')
                                 ->get();

        foreach ($dataVasel as $key => $item) {
            $array['dataVasel'][$item->id] = $item->count;
        }

        $finalArray = [];
        foreach ($array['label'] as $value) {
            $finalArray['label'][] = $value;
        }
        foreach ($array['dataResidegiShode'] as $value) {
            $finalArray['dataResidegiShode'][] = $value;
        }
        foreach ($array['dataVasel'] as $value) {
            $finalArray['dataVasel'][] = $value;
        }

        $number_of_complaints_per_type = [];

        $number_of_complaints_per_type['labels'] = $finalArray['label'];
        $number_of_complaints_per_type['datasets'][] = [
            'label' => 'رسیدگی شده',
            'data' => $finalArray['dataResidegiShode']
        ];
        $number_of_complaints_per_type['datasets'][] = [
            'label' => 'واصل شده',
            'data' => $finalArray['dataVasel']
        ];

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'number_of_complaints_per_type'],
            [
                'report_name' => 'number_of_complaints_per_type',
                'data' => $number_of_complaints_per_type,
            ]
        );
        // (END) [BI CONTROLLER => separationComplainTypeRahdariComplains]

        // (BEGIN) [CampController => statics] tool mehvarhaye asib dide
        $sql = "SELECT blockage_cause,blockage_cause_fa,COUNT(*) AS cnt,SUM(blockage_length) 
        AS lenght FROM camps WHERE is_open = 2 GROUP BY blockage_cause";
        $pies = DB::select(DB::raw($sql));

        $data = \App\Models\Camp::where('is_open', 2)
        ->groupBy('blockage_cause', 'axis_type')
        ->selectRaw('axis_type, axis_type_fa, blockage_cause, blockage_cause_fa, COUNT(*) AS cnt, SUM(blockage_length) as length')
        ->get()->toArray();

        $stack_result = [
            ['axis_type_fa' => 'آزادراه', 'data' => [['blockage_cause_fa' => 'برف', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سیل', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'رانش و ریزش', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سایر', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'طوفان شن', 'cnt' => 0, 'length' => 0]]],
            ['axis_type_fa' => 'اصلی', 'data' => [['blockage_cause_fa' => 'برف', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سیل', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'رانش و ریزش', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سایر', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'طوفان شن', 'cnt' => 0, 'length' => 0]]],
            ['axis_type_fa' => 'فرعی', 'data' => [['blockage_cause_fa' => 'برف', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سیل', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'رانش و ریزش', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سایر', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'طوفان شن', 'cnt' => 0, 'length' => 0]]],
            ['axis_type_fa' => 'روستایی', 'data' => [['blockage_cause_fa' => 'برف', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سیل', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'رانش و ریزش', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سایر', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'طوفان شن', 'cnt' => 0, 'length' => 0]]],
            ['axis_type_fa' => 'بزرگراه', 'data' => [['blockage_cause_fa' => 'برف', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سیل', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'رانش و ریزش', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'سایر', 'cnt' => 0, 'length' => 0], ['blockage_cause_fa' => 'طوفان شن', 'cnt' => 0, 'length' => 0]]],
        ];

        foreach ($data as $item) {
            $key = $item['axis_type'] - 1;

            foreach ($stack_result[$key]['data'] as $k => $axis_data) {
                if ($axis_data['blockage_cause_fa'] == $item['blockage_cause_fa']) {
                    $stack_result[$key]['data'][$k]['cnt'] = $item['cnt'];
                    $stack_result[$key]['data'][$k]['length'] = $item['length'];
                    break;
                }
            }
        }


        $sql = "SELECT money,car,rahdar,polbig+polsmall+other AS dmg, bl_len FROM(
            SELECT 
            --   COUNT(*) AS cnt,
              SUM(blockage_damage_money) AS money,
              SUM(blockage_damage_higher_6_count) AS polbig,
              SUM(blockage_damage_lower_6_count) AS polsmall,
              SUM(blockage_damage_count) AS other,
              SUM(active_cars_count) AS car,
              SUM(active_rahdar_count) AS rahdar,
              SUM(blockage_length) AS bl_len
            FROM
              camps
            WHERE is_open = 2
            )q";
        $statics = DB::select(DB::raw($sql));

        $mehvar_statistics = [
            'charts' => [
                'pies' => $pies,
                'stack' => $stack_result,
                'staticks' => $statics
            ]
        ];

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'mehvar_statistics'],
            [
                'report_name' => 'mehvar_statistics',
                'data' => $mehvar_statistics,
            ]
        );
        // (END) [CampController => statics] tool mehvarhaye asib dide

        // (BEGIN) [Posters Controller => progressinfo]
        $top_5_province_at_road_observation_according_to_progress_percent = DB::table('road_observeds')
            ->select(DB::raw('count(road_observeds.id) as count_number'), 'road_observeds.ProvinceName', DB::raw("(count(road_observeds.id) / (SELECT count(ro2.id) FROM road_observeds ro2  WHERE road_observeds.rms_province_id = ro2.rms_province_id)  * 100) as progress_percent"))
            ->where('road_observeds.rms_status', '<>', 0)
            ->groupBy('road_observeds.rms_province_id')
            ->orderBy('progress_percent', 'desc')
            ->limit(5)
            ->get();

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'top_provinces_according_to_number_of_complaints_handled'],
            [
                'report_name' => 'top_provinces_according_to_number_of_complaints_handled',
                'data' => $top_5_province_at_road_observation_according_to_progress_percent,
            ]
        );

        // (END) [Posters Controller => progressinfo]

        // (BEGIN) [Posters Controller => progressinfo] top_provinces_according_to_number_of_complaints_handled
        $top_5_province_at_road_observation_according_to_progress_percent = DB::table('road_observeds')
            ->select(DB::raw('count(road_observeds.id) as count_number'), 'road_observeds.ProvinceName', DB::raw("(count(road_observeds.id) / (SELECT count(ro2.id) FROM road_observeds ro2  WHERE road_observeds.rms_province_id = ro2.rms_province_id)  * 100) as progress_percent"))
            ->where('road_observeds.rms_status', '<>', 0)
            ->groupBy('road_observeds.rms_province_id')
            ->orderBy('progress_percent', 'desc')
            ->limit(5)
            ->get();

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'top_provinces_according_to_percent_of_complaints_handled'],
            [
                'report_name' => 'top_provinces_according_to_percent_of_complaints_handled',
                'data' => $top_5_province_at_road_observation_according_to_progress_percent,
            ]
        );

        // (END) [Posters Controller => progressinfo]

        // (BEGIN) [Posters Controller => progressinfo] top_provinces_according_to_number_of_complaints_handled
        $top_5_province_at_road_observation_according_to_quantity = DB::table('road_observeds')
            ->select('ProvinceName', DB::raw('count(id) as count_number'))
            ->where('rms_status', '<>', 0)
            ->groupBy('rms_province_id')
            ->orderBy('count_number', 'desc')
            ->limit(5)
            ->get();

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'top_provinces_according_to_number_of_complaints_handled'],
            [
                'report_name' => 'top_provinces_according_to_number_of_complaints_handled',
                'data' => $top_5_province_at_road_observation_according_to_quantity,
            ]
        );

        // (END) [Posters Controller => progressinfo]


        // (BEGIN) [Posters Controller => progressinfo] naqshe_faaliat_haye_rozaneh

        $provinces = Province::select('id', 'name_fa')->get();
        $array = [];

        $array = $this->createArrayFromProvincesOrCities($provinces, $array);

        $data = DB::table('road_items_projects')
        ->select('province_id', 'province_fa')
        ->whereBetween('created_at', [$from_date . ' 00:00:00', $to_date . ' 23:59:59'])
        ->get();

        $dataAfter = [];
        foreach ($data as $key => $value) {
            $dataAfter[$value->province_id - 1]['province_fa'] = $value->province_fa;
            $dataAfter[$value->province_id - 1]['province_id'] = $value->province_id;
            if(!isset($dataAfter[$value->province_id - 1]['count'])) {
                $dataAfter[$value->province_id - 1]['count'] = 0;
            }
            $dataAfter[$value->province_id - 1]['count']++;
        }

        $array = $this->createDataArray($dataAfter, $array);

        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            $finalArray['label'][] = $value;
            $finalArray['data'][] = $array['data'][$index];
        }

        $geoJsonArray = $finalArray['data'];

        array_multisort($finalArray['data'], SORT_DESC, $finalArray['label']);

        $myArray = [];

        $myArray['labels'] = $finalArray['label'];
        $myArray['datasets'][] = [
            'label' => 'نمودار وضعیت',
            'data' => $finalArray['data']
        ];

        ReportSummaryModel::updateOrCreate(
            ['report_name' => 'naqshe_faaliat_haye_rozaneh'],
            [
                'report_name' => 'naqshe_faaliat_haye_rozaneh',
                'data' => [
                    'data' => $myArray,
                    'geojson' => $geoJsonArray
                ],
            ]
        );
        // (END) [Posters Controller => progressinfo]
    }

    public function createArrayFromProvincesOrCities($collection, $array, $default = null)
    {
        $newArray = [];
        foreach ($collection as $key => $value) {
            $array['label'][$value->id] = $value->name_fa;
            $array['data'][$value->id] = $default;
        }

        return $array;
    }

    public function createDataArray($data, $array)
    {
        if(gettype($data) == 'array') {
            foreach ($data as $key => $item) {
                $array['data'][($item['province_id'] ?? $item['city_id'])] = $item['count'];
            }
        } else {
            foreach ($data as $key => $item) {
                $array['data'][($item->province_id ?? $item->city_id)] = $item->count;
            }
        }

        return $array;
    }
}
