<?php

namespace App\Http\Controllers;

use DB;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Barryvdh\Snappy\Facades\SnappyPdf;

use App\Models\User;
use App\Models\LogList;
use App\Models\Province;

class PostersController extends Controller
{
    public function develop(Request $request)
    {
        $request->fromDate = "2021-01-05 00:00:00";
        $request->toDate = "2021-01-05 23:59:59";
    }

    public function progressInfo(Request $request)
    {
        if(!auth()->user()->can('get_progress_info')){
            abort(403);
        }
        $request->fromDate = $request->fromDate ? $request->fromDate . " 00:00:00" : Carbon::now()->format('Y-m-d 00:00:00');
        $request->toDate = $request->toDate ? $request->toDate . " 23:59:59" : Carbon::now()->format('Y-m-d 23:59:59');

        $data['fromDate'] = $request->fromDate;
        $data['toDate'] = $request->toDate;

        // user part begin
        if ($request->province_id) {
            $users = User::where("province_id", $request->province_id)->get();
            $users_count = User::where("province_id", $request->province_id)->count();
        } else {
            $users = User::all();
            $users_count = User::all()->count();
        }

        foreach ($users as $index => $item) {
            if (!$index) {
                $ids_list = $item['id'];
            } else {
                $ids_list .= "," . $item['id'];
            }
        }

        $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 '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")
                        ) user_activity_distinct
                    GROUP BY yy,
                        mm,
                        dd,
                        hh,
                        user_id
                ) user_activity_by_hour_and_
            GROUP BY user_id) AS calculated_table;";

        $data['user_activity'] = (int) DB::select($user_activity_sql)[0]->activity;
        $user_activity_count_sql = "SELECT count(*) as cnt
                FROM user_activity_logs
                        WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")";
        $data['user_activity_count'] = (int)  DB::select($user_activity_count_sql)[0]->cnt;

        $user_activity_top_five_provinces_sql = "SELECT province_fa FROM(SELECT province_fa,COUNT(*) AS cnt  FROM user_activity_logs WHERE created_at BETWEEN '{$request->fromDate}' and '{$request->toDate}' GROUP BY province_id ORDER BY cnt DESC LIMIT 5)wq";
        $user_activity_top_five_provinces_by_users_sql = "SELECT province_fa FROM(SELECT cnt1,cnt2,A.province_fa,cnt2/cnt1 AS cnt
        FROM ( SELECT province_fa,province_id,COUNT(*) AS cnt1 FROM users  WHERE province_id IS NOT NULL GROUP BY province_id) AS A
        JOIN ( SELECT province_fa,province_id,COUNT(*) AS cnt2 FROM user_activity_logs WHERE created_at BETWEEN '{$request->fromDate}' and '{$request->toDate}' GROUP BY province_id) AS B
        
        ON A.province_id=B.province_id ORDER BY cnt DESC LIMIT 5)wq";
        $data['user_activity_top_five_provinces'] = (array)  DB::select($user_activity_top_five_provinces_sql);
        $data['user_activity_top_five_provinces_by_users'] = (array)  DB::select($user_activity_top_five_provinces_by_users_sql);
        // user part end

        // road items chart part begin
        $data['road_items_chart'] = DB::table('road_items_projects')
            ->select('item_fa as sub_item_fa', DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->groupBy('road_items_projects.item')
            ->orderBy('count_number', 'desc')
            ->limit(5)
            ->get();
        // road items chart part end

        // road items all count part begin
        $data['road_items_sum'] = 0;
        foreach ($data['road_items_chart'] as $key => $value) {
            $data['road_items_sum'] += $value->count_number;
        }
        // road items all count part end


        //  contract_sub_items
        if (!$request->province_id) {
            $data['contract_subs_group_by_items'] = DB::table('contract_subitems')
                ->select('project_type_fa', DB::raw('count(*) as count_number'))
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->groupBy('project_type_fa')
                ->orderBy('project_type_id')
                ->get()->toArray();
        }
        /// end contract_sub_items
        // top 5 province at road item part begin
        if (!$request->province_id) {
            $data['top_5_province_at_road_item'] = DB::table('road_items_projects')
                ->select('province_fa', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->groupBy('road_items_projects.province_id')
                ->orderBy('count_number', 'desc')
                ->limit(5)
                ->get();
        }
        // top 5 province at road item part end

        // bottom 5 province at road item part begin
        if (!$request->province_id) {
            $data['bottom_5_province_at_road_item'] = DB::table('road_items_projects')
                ->select('province_fa', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->groupBy('road_items_projects.province_id')
                ->orderBy('count_number')
                ->limit(5)
                ->get();
        }
        // bottom 5 province at road item part end
        ////////   geo_json for road items

        if (!$request->province_id) {
            //////
            $array_for_this_function = [];
            $provinces_for_this_function = Province::select('id', 'name_fa')->get();
            $array_for_this_function = self::createArrayFromProvincesOrCities($provinces_for_this_function, $array_for_this_function);
            $data_temp_for_this_function = DB::table('road_items_projects') /////// miladddddddddd ////['road_item_group_by_province']
                ->select('province_fa', 'province_id', DB::raw('count(id) as count'))
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->groupBy('road_items_projects.province_id')
                ->orderBy('province_id')
                ->get();
            $array_for_this_function = self::createDataArray($data_temp_for_this_function, $array_for_this_function);
            $finalArray_for_this_function = [];
            foreach ($array_for_this_function['label'] as $index => $value) {
                $finalArray_for_this_function['data'][] = $array_for_this_function['data'][$index];
            }
            $data['road_item_group_by_province'] = $finalArray_for_this_function;
            //////

            $road_item_group_province_chunk_sql = "SELECT AA.name_fa as province_fa, IF(B.cnt IS NOT NULL ,B.cnt,0) AS cnt
                                                    FROM ( SELECT id, name_fa, 0 AS cnt FROM provinces) AS AA
                                                    LEFT JOIN (
                                                    SELECT A.cnt_province/B.cnt_users AS cnt,A.province_fa FROM
                                                    (SELECT COUNT(*) AS cnt_province,province_id,province_fa FROM road_items_projects WHERE created_At BETWEEN '" . $request->fromDate . "' and '" . $request->toDate . "' GROUP BY province_id)A JOIN 
                                                    (SELECT COUNT(*) AS cnt_users ,province_id, province_fa FROM users  WHERE province_id IS NOT NULL GROUP BY province_id)B
                                                    ON A.province_id = B.province_id) AS B 
                                                    ON AA.name_fa=B.province_fa
                                                    ORDER BY cnt DESC";
            $data['road_item_group_province_chunk'] = DB::select($road_item_group_province_chunk_sql);
        }
        // geojson chart end
        //// end geo
        // fast react chart part begin
        /// mostapha
        // $data['fast_react_chart'] = DB::table('road_observeds')
        //     ->select(DB::raw('count(id) as count_number,rms_status'))
        //     ->when($request->province_id, function ($query) use ($request) {
        //         return $query->where('rms_province_id', $request->province_id);
        //     })
        //     ->whereBetween('created_at', [$request->fromDate, $request->toDate])
        //     ->groupBy('rms_status')
        //     ->get();
        ////// milad
        $fast_ract_chart_sql = "SELECT st,ttt/sumall * 100 AS percent FROM(SELECT st,SUM(tt) AS ttt,SUM(tt) OVER () AS sumall  FROM(SELECT IF(rms_status > 0, 1, 0) AS st,COUNT(*) AS tt FROM road_observeds where created_at between '" . $request->fromDate . "' and '" . $request->toDate . "' GROUP BY st)a GROUP BY st)q order by st";
        $data['fast_react_chart'] = (array)  DB::select($fast_ract_chart_sql);

        $data['fast_react_group_by_type'] = DB::table('road_observeds')
            ->select(DB::raw('count(*) as cnt,FeatureTypeTitle,fk_FeatureType'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('rms_province_id', $request->province_id);
            })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->where('rms_status', '<>', 0)
            ->groupBy('fk_FeatureType')
            ->orderBy('fk_FeatureType')
            ->get();
        $amir = ['1' => 0, '2' => 0, '3' => 0, '4' => 0, '5' => 0, '6' => 0];
        foreach ($data['fast_react_group_by_type'] as $key => $value) {
            $amir[$value->fk_FeatureType] = $value->cnt;
        }
        $data['fast_react_group_by_type'] = $amir;
        ////// milad
        // fast react chart part end

        // top 5 province at road observation according to quantity part begin
        if (!$request->province_id) {
            $data['top_5_province_at_road_observation_according_to_quantity'] = DB::table('road_observeds')
                ->select('ProvinceName', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('rms_province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->where('rms_status', '<>', 0)
                ->groupBy('rms_province_id')
                ->orderBy('count_number', 'desc')
                ->limit(5)
                ->get();
        }
        // top 5 province at road observation according to quantity part end

        // bottom 5 province at road observation according to quantity part begin
        if (!$request->province_id) {
            $data['bottom_5_province_at_road_observation_according_to_quantity'] = DB::table('road_observeds')
                ->select('ProvinceName', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('rms_province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                ->where('rms_status', '<>', 0)
                ->groupBy('rms_province_id')
                ->orderBy('count_number')
                ->limit(5)
                ->get()->toArray();
        }
        // bottom 5 province at road observation according to quantity part end

        // top 5 province at road observation according to progress percent part begin
        if (!$request->province_id) {
            $data['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 and ro2.created_at between '" . $request->fromDate . "' and '" . $request->toDate . "')  * 100) as progress_percent"))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('rms_province_id', $request->province_id);
                })
                ->whereBetween('road_observeds.created_at', [$request->fromDate, $request->toDate])
                ->where('road_observeds.rms_status', '<>', 0)
                ->groupBy('road_observeds.rms_province_id')
                ->orderBy('progress_percent', 'desc')
                ->limit(5)
                ->get();
        }
        // top 5 province at road observation according to progress percent part end

        // bottom 5 province at road observation according to progress percent part begin
        if (!$request->province_id) {
            $data['bottom_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 and ro2.created_at between '" . $request->fromDate . "' and '" . $request->toDate . "') * 100) as progress_percent"))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('rms_province_id', $request->province_id);
                })
                ->whereBetween('road_observeds.created_at', [$request->fromDate, $request->toDate])
                ->where('road_observeds.rms_status', '<>', 0)
                ->groupBy('road_observeds.rms_province_id')
                ->orderBy('progress_percent')
                ->limit(5)
                ->get()->toArray();
        }
        // bottom 5 province at road observation according to progress percent part end

        // road patrol count and distance part begin
        $data['road_patrol_part'] = DB::table('road_patrols')
            ->select(DB::raw('sum(distance) as distance_sum, count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->get();
        // road patrol count and distance part end

        // road patrol count part begin
        // $data['road_tollhouse_count_status'] = DB::table('rahdari_points')
        //         ->select(DB::raw('count(id) as count_number,status'))
        //         ->when($request->province_id, function ($query) use ($request) {
        //             return $query->where('province_id', $request->province_id);
        //         })
        //     ->groupBy('status')
        //     ->get();
        $road_tollhouse_count_status_sql = "SELECT st,round(ttt/sumall,2)  AS percent FROM(SELECT st,SUM(tt) AS ttt,SUM(tt) OVER () AS sumall  FROM(SELECT IF(STATUS > 0, 1, 0) AS st,COUNT(*) AS tt FROM rahdari_points  GROUP BY st)a GROUP BY st)q ORDER BY st";
        $data['road_tollhouse_count_status'] = DB::select($road_tollhouse_count_status_sql); /////// faal va gheyre faal
        $road_tollhouse_count_type_sql = "SELECT st,round(ttt/sumall, 2)  AS percent FROM(SELECT st,SUM(tt) AS ttt,SUM(tt) OVER () AS sumall  FROM(SELECT IF(TYPE > 2, 1, 0) AS st,COUNT(*) AS tt FROM rahdari_points  GROUP BY st)a GROUP BY st)q 
            WHERE st =1
            ORDER BY st ";
        $data['road_tollhouse_count_type'] = DB::select($road_tollhouse_count_type_sql)[0]->percent; //// movaghat

        $road_tollhouse_spec_sql = "SELECT SUM(team_num) AS ekip,SUM(staff_num) AS rahdar,SUM(machines_heavy) AS sangin, SUM(machines_sheavy) AS nime_sangin,COUNT(*) AS rahdarkhone FROM rahdari_points";
        $data['road_tollhouse_spec'] = DB::select($road_tollhouse_spec_sql); //// movaghat
        // road patrol count part end

        // road patrol updated part begin
        // $data['road_updated_tollhouse_count'] = DB::table('rahdari_points')
        //         ->select(DB::raw('count(id) as count_number'))
        //         ->when($request->province_id, function ($query) use ($request) {
        //             return $query->where('province_id', $request->province_id);
        //         })
        //         ->whereBetween('updated_at', [$request->fromDate, $request->toDate])
        //     // ->groupBy('status')
        //     ->get();
        // road patrol updated part end

        // active user count begin
        $active_user_count_sql = "
            SELECT  COUNT(*) AS active_user_count
            FROM(
                SELECT 
                    user_id
                FROM user_activity_logs
                WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")
                GROUP BY user_id
            ) grpuped_by_user_id";

        $data['active_user_count'] = DB::select($active_user_count_sql)[0]->active_user_count;
        // active user count begin


        // user activity chart count begin

        $quantitative_activity_chart_sql = "
        SELECT created_at,
                COUNT(*) AS quantity
            FROM (
                    SELECT 
                        created_at,
                        YEAR (created_at) AS yy,
                        MONTH (created_at) AS mm,
                        DAY (created_at) AS dd
                    FROM user_activity_logs
                    WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")
                ) user_activity_distinct
                GROUP BY 
                yy,
                mm,
                dd ;";

        $hourly_activity_chart_sql = "
            SELECT created_at,
                COUNT(quantity) AS majmoe
            FROM (
                    SELECT *,
                        COUNT(*) AS quantity
                    FROM (
                            SELECT 
                                *
                            FROM user_activity_logs
                            WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")
                        ) user_activity_distinct
                    GROUP BY yy,
                        mm,
                        dd,
                        hh,
                        user_id
                ) user_activity_by_hour_and_
            GROUP BY 
                yy,
                mm,
                dd;";
        // $hourly_activity_chart_sql = "
        //     SELECT created_at,
        //         COUNT(quantity) AS majmoe
        //     FROM (
        //             SELECT *,
        //                 COUNT(*) AS quantity
        //             FROM (
        //                     SELECT
        //                         *,
        //                         YEAR (created_at) AS yy,
        //                         MONTH (created_at) AS mm,
        //                         HOUR (created_at) AS hh,
        //                         DAY (created_at) AS dd
        //                     FROM user_activity_logs
        //                     WHERE created_at between '{$request->fromDate}' and '{$request->toDate}' and user_id IN(" . $ids_list . ")
        //                 ) user_activity_distinct
        //             GROUP BY yy,
        //                 mm,
        //                 dd,
        //                 hh,
        //                 user_id
        //         ) user_activity_by_hour_and_
        //     GROUP BY
        //         yy,
        //         mm,
        //         dd;";
        $data['hourly_activity_chart'] = $ids_list ? DB::select($hourly_activity_chart_sql) : null;
        $data['quantitative_activity_chart'] = $ids_list ? DB::select($quantitative_activity_chart_sql) : null;
        // user activity chart count begin

        // geojson chart begin
        $array = [];

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

        if (!$request->province_id) {
            $array = self::createArrayFromProvincesOrCities($provinces, $array);
        }

        $data_temp = DB::table('contract_subitems')
            ->select('province_id', 'province_fa', DB::raw('round(avg(progress_project), 1) as count, count(progress_project) as count_number'))
            ->groupBy('province_id')
            ->when($request->province_id, function ($query, $request) {
                return $query->where('province_id', $request->province_id)
                    ->select('city_id', 'city_fa', DB::raw('round(avg(progress_project), 1) as count, count(progress_project) as count_number'))
                    ->groupBy('city_id');
            })
            ->when($request->fromDate, function ($query) use ($request) {
                return $query->whereBetween('contract_date_from_parent_contract', [$request->fromDate, $request->toDate]);
            })
            ->orderBy('province_id')
            ->get();
        $array = self::createDataArray($data_temp, $array);
        $array_for_number = self::createDataArrayForCountNumber($data_temp, $array);

        $finalArray = [];
        foreach ($array['label'] as $index => $value) {
            if ($array_for_number['data'][$index] == null) {
                $finalArray['label'][] = $value;
                $finalArray['data'][] = null;
            } else {
                $finalArray['label'][] = $value . " (" . number_format($array_for_number['data'][$index]) . ")";
                $finalArray['data'][] = $array['data'][$index];
            }
        }
        $geoJsonArray = $finalArray['data'];
        $data['provinces'] = \App\Models\Province::select("*")->orderBy("id")->get();
        // HomeContentController@getAllProvinces
        // array_multisort($finalArray['data'], SORT_DESC, $finalArray['label']);
        $data['geojson_chart'] = $finalArray;
        // geojson chart end


        // top 5 province at road patrol according to quantity part begin
        if (!$request->province_id) {
            $data['top_5_province_at_road_patrol_according_to_quantity'] = DB::table('road_patrols')
                ->select('province_fa', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                // ->where('rms_status', '<>', 0)
                ->groupBy('province_id')
                ->orderBy('count_number', 'desc')
                ->limit(5)
                ->get();
        }
        // top 5 province at road patrol according to quantity part end

        // bottom 5 province at road patrol according to quantity part begin
        if (!$request->province_id) {
            $data['bottom_5_province_at_road_patrol_according_to_quantity'] = DB::table('road_patrols')
                ->select('province_fa', DB::raw('count(id) as count_number'))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                // ->where('rms_status', '<>', 0)
                ->groupBy('province_id')
                ->orderBy('count_number')
                ->limit(5)
                ->get();
        }
        // bottom 5 province at road patrol according to quantity part end

        // top 5 province at road patrol according to avarage distance part begin
        if (!$request->province_id) {
            $data['top_5_province_at_road_patrol_according_to_avarage_distance'] = DB::table('road_patrols')
                ->select(DB::raw('count(road_patrols.id) as count_number'), 'road_patrols.province_fa', DB::raw("(count(road_patrols.id) / (SELECT sum(ro2.distance) FROM road_patrols ro2  WHERE road_patrols.province_id = ro2.province_id and ro2.created_at between '" . $request->fromDate . "' and '" . $request->toDate . "')  * 100) as avarage_distance"))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('road_patrols.created_at', [$request->fromDate, $request->toDate])
                // ->where('road_patrols.rms_status', '<>', 0)
                ->groupBy('road_patrols.province_id')
                ->orderBy('avarage_distance', 'desc')
                ->limit(5)
                ->get()->toArray();
        }
        // top 5 province at road patrol according to avarage distance part end

        // bottom 5 province at road patrol according to avarage distance part begin
        if (!$request->province_id) {
            $data['bottom_5_province_at_road_patrol_according_to_avarage_distance'] = DB::table('road_patrols')
                ->select(DB::raw('count(road_patrols.id) as count_number'), 'road_patrols.province_fa', DB::raw("(count(road_patrols.id) / (SELECT sum(ro2.distance) FROM road_patrols ro2  WHERE road_patrols.province_id = ro2.province_id and ro2.created_at between '" . $request->fromDate . "' and '" . $request->toDate . "') * 100) as avarage_distance"))
                ->when($request->province_id, function ($query) use ($request) {
                    return $query->where('province_id', $request->province_id);
                })
                ->whereBetween('road_patrols.created_at', [$request->fromDate, $request->toDate])
                // ->where('road_patrols.rms_status', '<>', 0)
                ->groupBy('road_patrols.province_id')
                ->orderBy('avarage_distance')
                ->limit(5)
                ->get();
        }
        // bottom 5 province at road patrol according to avarage distance part end

        // proposals part begin
        $data['proposals']['in_the_interval'] = DB::table('proposals')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->get()[0]->count_number;

        $data['proposals']['whole'] = DB::table('proposals')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->get()[0]->count_number;
        // proposals part end

        // lawmaker part begin
        $data['lawmaker']['in_the_interval'] = DB::table('lawmakers_correspondences')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->get()[0]->count_number;

        $data['lawmaker']['whole'] = DB::table('lawmakers_correspondences')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->get()[0]->count_number;
        // lawmaker part end

        // progress percent avarage begin
        $data['contracts']['avarage'] = DB::table('contract_subitems')
            ->select(DB::raw('avg(progress_project) as avarage'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->get()[0]->avarage;

        $data['contracts']['progressed_sum'] = DB::table('contract_subitems')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->where('last_status_id', 2)
            ->get()[0]->count_number;

        $data['contracts']['done_sum'] = DB::table('contract_subitems')
            ->select(DB::raw('count(id) as count_number'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            ->where('last_status_id', 3)
            ->get()[0]->count_number;

        $data['contracts']['last_digit_project'] = DB::table('contract_subitems')
            ->select(DB::raw('sum(last_digit_project) as sum_last_digit_project'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            // ->where('last_status_id',3)
            ->get()[0]->sum_last_digit_project;

        $data['contracts']['last_function_operator'] = DB::table('contract_subitems')
            ->select(DB::raw('sum(last_function_operator) as sum_last_function_operator'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            // ->where('last_status_id',3)
            ->get()[0]->sum_last_function_operator;

        $data['contracts']['last_payable_operator'] = DB::table('contract_subitems')
            ->select(DB::raw('sum(last_payable_operator) as sum_last_payable_operator'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            // ->where('last_status_id',3)
            ->get()[0]->sum_last_payable_operator;

        $data['contracts']['complete_payable'] = DB::table('contract_subitems')
            ->select(DB::raw('sum(complete_payable) as sum_complete_payable'))
            ->when($request->province_id, function ($query) use ($request) {
                return $query->where('province_id', $request->province_id);
            })
            // ->where('last_status_id',3)
            ->get()[0]->sum_complete_payable;

        $data['contracts']['top_5_province_avarage_progress'] = DB::table('contract_subitems')
            ->select('province_fa', DB::raw('round(avg(progress_project)) as avarage'))
            ->groupBy('province_id')
            // ->when($request->province_id, function ($query, $request) {
            //     return $query->where('province_id', $request->province_id)
            //         ->select('city_id', 'city_fa', DB::raw('round(avg(progress_project), 1) as count, count(progress_project) as count_number'))
            //         ->groupBy('city_id');
            // })
            ->when($request->fromDate, function ($query) use ($request) {
                return $query->whereBetween('last_date_update', [$request->fromDate, $request->toDate]);
            })
            ->orderBy('avarage', 'desc')
            ->limit(5)
            ->get()->toArray();
        // $query =  "SELECT COUNT(
        //     CASE
        //         WHEN progress_project > 0 THEN 1
        //     END
        //     ) AS qty,
        //     ROUND(AVG(progress_project)) AS progress_project,project_type_fa,
        //     project_type_id
        // FROM (
        //         SELECT unique_code,
        //             date_,
        //             province_id,
        //             province_fa,
        //             MAX(progress_project) - MIN(progress_project) AS progress_project,
        //             project_type_fa,
        //             project_type_id
        //         FROM (
        //                 SELECT project_type_id,
        //                     unique_code,
        //                     last_date_update AS date_,
        //                     province_id,
        //                     province_fa,
        //                     operation_type_id1,
        //                     operation_type_amount1,
        //                     operation_type_progress1,
        //                     operation_type_tonaj1,
        //                     operation_type_id2,
        //                     operation_type_amount2,
        //                     operation_type_progress2,
        //                     operation_type_tonaj2,
        //                     operation_type_id3,
        //                     operation_type_amount3,
        //                     operation_type_progress3,
        //                     operation_type_tonaj3,
        //                     operation_type_id4,
        //                     operation_type_amount4,
        //                     operation_type_progress4,
        //                     operation_type_tonaj4,
        //                     progress_project,
        //                     project_type_fa
        //                 FROM contract_subitems
        //                 UNION
        //                 SELECT project_type_id,
        //                     unique_code,
        //                     last_date_update AS date_,
        //                     province_id,
        //                     province_fa,
        //                     operation_type_id1,
        //                     operation_type_amount1,
        //                     operation_type_progress1,
        //                     operation_type_tonaj1,
        //                     operation_type_id2,
        //                     operation_type_amount2,
        //                     operation_type_progress2,
        //                     operation_type_tonaj2,
        //                     operation_type_id3,
        //                     operation_type_amount3,
        //                     operation_type_progress3,
        //                     operation_type_tonaj3,
        //                     operation_type_id4,
        //                     operation_type_amount4,
        //                     operation_type_progress4,
        //                     operation_type_tonaj4,
        //                     progress_project,
        //                     project_type_fa
        //                 FROM contract_sub_items_histories
        //             ) AS merged_table
        //         -- WHERE project_type_id = 1
        //         GROUP BY unique_code
        //     ) AS mreged_statistics_table GROUP BY project_type_id WHERE 1=1  ";
        $query = "     SELECT  idd AS id,average,progress_project AS progress,date_   FROM (        
                SELECT * 
          FROM(SELECT COUNT( 
                          CASE
                              WHEN progress_project > 0 THEN 1
                          END
                          ) AS qty,
                          ROUND(AVG(progress_project)) AS progress_project,project_type_fa,
                          project_type_id,date_
                      FROM (
                              SELECT unique_code,
                                  date_,
                                  province_id,
                                  province_fa,
                                  MAX(progress_project) - MIN(progress_project) AS progress_project,
                                  project_type_fa,
                                  project_type_id
                              FROM (
                                      SELECT project_type_id,
                                          unique_code,
                                          last_date_update AS date_,
                                          province_id,
                                          province_fa,
                                          operation_type_id1,
                                          operation_type_amount1,
                                          operation_type_progress1,
                                          operation_type_tonaj1,
                                          operation_type_id2,
                                          operation_type_amount2,
                                          operation_type_progress2,
                                          operation_type_tonaj2,
                                          operation_type_id3,
                                          operation_type_amount3,
                                          operation_type_progress3,
                                          operation_type_tonaj3,
                                          operation_type_id4,
                                          operation_type_amount4,
                                          operation_type_progress4,
                                          operation_type_tonaj4,
                                          progress_project,
                                          project_type_fa
                                      FROM contract_subitems
                                      UNION
                                      SELECT project_type_id,
                                          unique_code,
                                          last_date_update AS date_,
                                          province_id,
                                          province_fa,
                                          operation_type_id1,
                                          operation_type_amount1,
                                          operation_type_progress1,
                                          operation_type_tonaj1,
                                          operation_type_id2,
                                          operation_type_amount2,
                                          operation_type_progress2,
                                          operation_type_tonaj2,
                                          operation_type_id3,
                                          operation_type_amount3,
                                          operation_type_progress3,
                                          operation_type_tonaj3,
                                          operation_type_id4,
                                          operation_type_amount4,
                                          operation_type_progress4,
                                          operation_type_tonaj4,
                                          progress_project,
                                          project_type_fa
                                      FROM contract_sub_items_histories
                                  ) AS merged_table
                              -- WHERE project_type_id = 1
                              GROUP BY unique_code
                          ) AS mreged_statistics_table where date_ BETWEEN '{$request->fromDate}' AND '{$request->toDate}' GROUP BY project_type_id)Aa
          
          JOIN (
          
          SELECT ROUND(AVG(progress_project)) AS average,project_type_id AS idd FROM contract_subitems where  last_date_update BETWEEN '{$request->fromDate}' AND '{$request->toDate}' GROUP BY idd)Bb
          
          ON Aa.project_type_id=Bb.idd
          )q  WHERE 1=1  ";

        if ($request->province_id) {
            $query .= " AND province_id = {$request->province_id}";
        }

        $query .= " AND date_ BETWEEN '{$request->fromDate}' AND '{$request->toDate}'";

        // $query .= " GROUP BY province_idORDER BY province_id ASC;";
        $query .=  " ORDER BY average DESC";
        $data['contracts']['progress_avrage'] = DB::select($query);

        $data['contracts']['progress_avrage_according_province'] = $this->progressAvrageAccordingProvince($request);
        $data['contracts']['top_5_progress_avrage_according_province'] = $this->top5ProgressAvrageAccordingProvince($request);

        $query = "SELECT last_status_fa AS fa, last_status_id, ROUND(COUNT(*)/(SELECT COUNT(*) FROM contract_subitems WHERE last_date_update BETWEEN '{$request->fromDate}' AND '{$request->toDate}'),2) AS percent FROM contract_subitems WHERE last_date_update BETWEEN '{$request->fromDate}' AND '{$request->toDate}' GROUP BY last_status_id";

        $data['contracts']['done_and_in_progress'][1]['fa'] = 'درصد پروژه های درحال تجهیز کارگاه';
        $data['contracts']['done_and_in_progress'][1]['percent'] = 0;

        $data['contracts']['done_and_in_progress'][2]['fa'] = 'درصد پروژه های در حال اجرا';
        $data['contracts']['done_and_in_progress'][2]['percent'] = 0;


        $data['contracts']['done_and_in_progress'][3]['fa'] = 'درصد پروژه های خاتمه یافته';
        $data['contracts']['done_and_in_progress'][3]['percent'] = 0;

        $data['contracts']['done_and_in_progress'][4]['fa'] = 'درصد پروژه های در دست مناقصه';
        $data['contracts']['done_and_in_progress'][4]['percent'] = 0;

        // $data['contracts']['done_and_in_progress'] = DB::select(DB::raw($query));
        // dd(DB::select(DB::raw($query)));
        foreach (DB::select($query) as $key => $value) {
            $data['contracts']['done_and_in_progress'][$value->last_status_id]['percent'] = $value->percent;
        }
        // dd($data['contracts']['done_and_in_progress']);
        $query = "SELECT province_fa FROM(SELECT ROUND(AVG(progress_project)) AS progress_project,date_,province_id,province_fa
        FROM (
                SELECT unique_code,
                    date_,
                    province_id,
                    province_fa,
                    MAX(progress_project) - MIN(progress_project) AS progress_project,
                    project_type_fa,
                    project_type_id
                FROM (
                        SELECT project_type_id,
                            unique_code,
                            last_date_update AS date_,
                            province_id,
                            province_fa,
                            operation_type_id1,
                            operation_type_amount1,
                            operation_type_progress1,
                            operation_type_tonaj1,
                            operation_type_id2,
                            operation_type_amount2,
                            operation_type_progress2,
                            operation_type_tonaj2,
                            operation_type_id3,
                            operation_type_amount3,
                            operation_type_progress3,
                            operation_type_tonaj3,
                            operation_type_id4,
                            operation_type_amount4,
                            operation_type_progress4,
                            operation_type_tonaj4,
                            progress_project,
                            project_type_fa,
                            last_status_id
                        FROM contract_subitems 
                        UNION
                        SELECT project_type_id,
                            unique_code,
                            last_date_update AS date_,
                            province_id,
                            province_fa,
                            operation_type_id1,
                            operation_type_amount1,
                            operation_type_progress1,
                            operation_type_tonaj1,
                            operation_type_id2,
                            operation_type_amount2,
                            operation_type_progress2,
                            operation_type_tonaj2,
                            operation_type_id3,
                            operation_type_amount3,
                            operation_type_progress3,
                            operation_type_tonaj3,
                            operation_type_id4,
                            operation_type_amount4,
                            operation_type_progress4,
                            operation_type_tonaj4,
                            progress_project,
                            project_type_fa,
                            last_status_id
                        FROM contract_sub_items_histories 
                    ) AS merged_table
                 WHERE last_status_id = 2
                GROUP BY unique_code
            ) AS mreged_statistics_table WHERE date_ BETWEEN '{$request->fromDate}' AND '{$request->toDate}'   GROUP BY province_id )q WHERE progress_project = 0";
        $data['contracts']['province_zero_progress'] = DB::select($query);
        $data['contracts']['max_contracts_group_by_province'] = DB::table('contract_subitems')
            ->select('province_fa', DB::raw('count(*) as count_number'))
            // ->when($request->province_id, function ($query) use ($request) {
            //     return $query->where('province_id', $request->province_id);
            // })
            ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->groupBy('province_id')
            ->orderBy('count_number', 'desc')
            ->limit(5)
            ->get()->toArray();
        // progress percent avarage end

        $data['users_count'] = $users_count;
        if (!$request->province_id) {
            $data['road_item_cluster'] = DB::table('road_items_projects') /////// miladddddddddd ////['road_item_group_by_province']
                ->select('start_lat as 0', 'start_lng as 1')
                ->whereBetween('created_at', [$request->fromDate, $request->toDate])
                // ->groupBy('road_items_projects.province_id')
                // ->orderBy('province_id')
                ->get()->toArray();
        }
        if ($request->develop == 1) {
            dd($data);
        } else if ($request->develop == 'pdf') {

            $pdf = SnappyPdf::loadView('posters.progress_info', compact("data"));
            return $pdf->download('ine.pdf');
        } else {
            return view('posters.progress_info', compact("data"));
        }
    }

    public function progressInfodevelop(Request $request)
    {
    }

    public static 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 static 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;
    }

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

        return $array;
    }
    public function develooooooo0p(Request $request)
    {



        $fromDate = "2021-12-20 00:00:00";
        $toDate = "2022-01-15 23:59:59";
        $query = "SELECT province_fa FROM(SELECT ROUND(AVG(progress_project)) AS progress_project,date_,province_id,province_fa
        FROM (
                SELECT unique_code,
                    date_,
                    province_id,
                    province_fa,
                    MAX(progress_project) - MIN(progress_project) AS progress_project,
                    project_type_fa,
                    project_type_id
                FROM (
                        SELECT project_type_id,
                            unique_code,
                            last_date_update AS date_,
                            province_id,
                            province_fa,
                            operation_type_id1,
                            operation_type_amount1,
                            operation_type_progress1,
                            operation_type_tonaj1,
                            operation_type_id2,
                            operation_type_amount2,
                            operation_type_progress2,
                            operation_type_tonaj2,
                            operation_type_id3,
                            operation_type_amount3,
                            operation_type_progress3,
                            operation_type_tonaj3,
                            operation_type_id4,
                            operation_type_amount4,
                            operation_type_progress4,
                            operation_type_tonaj4,
                            progress_project,
                            project_type_fa,
                            last_status_id
                        FROM contract_subitems 
                        UNION
                        SELECT project_type_id,
                            unique_code,
                            last_date_update AS date_,
                            province_id,
                            province_fa,
                            operation_type_id1,
                            operation_type_amount1,
                            operation_type_progress1,
                            operation_type_tonaj1,
                            operation_type_id2,
                            operation_type_amount2,
                            operation_type_progress2,
                            operation_type_tonaj2,
                            operation_type_id3,
                            operation_type_amount3,
                            operation_type_progress3,
                            operation_type_tonaj3,
                            operation_type_id4,
                            operation_type_amount4,
                            operation_type_progress4,
                            operation_type_tonaj4,
                            progress_project,
                            project_type_fa,
                            last_status_id
                        FROM contract_sub_items_histories 
                    ) AS merged_table
                 WHERE last_status_id = 2
                GROUP BY unique_code
            ) AS mreged_statistics_table WHERE date_ BETWEEN '{$fromDate}' AND '{$toDate}'   GROUP BY province_id )q WHERE progress_project = 0";
        $data['contracts']['province_zero_progress'] = DB::select(DB::raw($query));
        $data['contracts']['max_contracts_group_by_province'] = DB::table('contract_subitems')
            ->select('province_fa', DB::raw('count(*) as count_number'))
            // ->when($request->province_id, function ($query) use ($request) {
            //     return $query->where('province_id', $request->province_id);
            // })
            // ->whereBetween('created_at', [$request->fromDate, $request->toDate])
            ->groupBy('province_id')
            ->orderBy('count_number', 'desc')
            ->limit(5)
            ->get()->toArray();
        dd($data);
    }


    public function progressAvrageAccordingProvince($request)
    {
        $query =  "SELECT COUNT( 
                 CASE
                     WHEN progress_project > 0 THEN 1
                 END
                 ) AS qty,
                 ROUND(AVG(progress_project)) AS progress_project,
                 province_id,
                 province_fa
             FROM (
                     SELECT unique_code,
                         date_,
                         province_id,
                         province_fa,
                         MAX(progress_project) - MIN(progress_project) AS progress_project,
                         project_type_id
                     FROM (
                             SELECT project_type_id,
                                 unique_code,
                                 last_date_update AS date_,
                                 province_id,
                                 province_fa,
                                 operation_type_id1,
                                 operation_type_id2,
                                 operation_type_id3,
                                 operation_type_id4,
                                 progress_project
                             FROM contract_subitems
                             UNION
                             SELECT project_type_id,
                                 unique_code,
                                 last_date_update AS date_,
                                 province_id,
                                 province_fa,
                                 operation_type_id1,
                                 operation_type_id2,
                                 operation_type_id3,
                                 operation_type_id4,
                                 progress_project
                             FROM contract_sub_items_histories
                         ) AS merged_table
                     GROUP BY unique_code
                 ) AS mreged_statistics_table WHERE 1=1  ";

        if ($request->province_id) {
            $query .= " AND province_id = {$request->province_id}";
        }

        $query .= " AND date_ BETWEEN '{$request->fromDate}' AND '{$request->toDate}'";
        $query .=  " GROUP BY province_id order by province_id";

        $temp_finalArray = [];
        foreach (Province::all() as $key => $value) {
            // $temp_finalArray[$value->id]['label'] = $value->name_fa;
            $temp_finalArray[$value->id] = null;
        }
        foreach (DB::select($query) as $key => $value) {
            $temp_finalArray[$value->province_id] = $value->progress_project;
        }
        foreach ($temp_finalArray as $key => $value) {
            $finalArray[] = $value;
        }
        // dd($finalArray);
        return $finalArray;
    }


    public function top5ProgressAvrageAccordingProvince($request)
    {
        $query =  "SELECT ROUND(AVG(progress_project)) AS progress_project,
                 province_fa
             FROM (
                     SELECT unique_code,
                         date_,
                         province_id,
                         province_fa,
                         MAX(progress_project) - MIN(progress_project) AS progress_project,
                         project_type_id
                     FROM (
                             SELECT project_type_id,
                                 unique_code,
                                 last_date_update AS date_,
                                 province_id,
                                 province_fa,
                                 operation_type_id1,
                                 operation_type_id2,
                                 operation_type_id3,
                                 operation_type_id4,
                                 progress_project
                             FROM contract_subitems
                             UNION
                             SELECT project_type_id,
                                 unique_code,
                                 last_date_update AS date_,
                                 province_id,
                                 province_fa,
                                 operation_type_id1,
                                 operation_type_id2,
                                 operation_type_id3,
                                 operation_type_id4,
                                 progress_project
                             FROM contract_sub_items_histories
                         ) AS merged_table
                     GROUP BY unique_code
                 ) AS mreged_statistics_table WHERE 1=1  ";

        if ($request->province_id) {
            $query .= " AND province_id = {$request->province_id}";
        }

        $query .= " AND date_ BETWEEN '{$request->fromDate}' AND '{$request->toDate}'";
        $query .=  " GROUP BY province_id ORDER BY progress_project DESC limit 5";

        // $finalArray = [];
        // foreach (Province::all() as $key => $value) {
        //     $finalArray[$value->id]['label'] = $value->name_fa;
        //     $finalArray[$value->id]['progress_project'] = null;
        // }
        // foreach (DB::select(DB::raw($query)) as $key => $value) {
        //     $finalArray[$value->province_id]['progress_project'] = $value->progress_project;
        // }
        // dd(DB::select(DB::raw($query)));
        return DB::select($query);
    }
}
