<?php

namespace App\Http\Controllers;

use SoapFault;
use SoapClient;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use Morilog\Jalali\Jalalian;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Barryvdh\Snappy\Facades\SnappyPdf;
use App\Models\RoadObservationHistory;
use App\Models\RoadObserved;
use App\Models\City;
use App\Models\User;
use App\Models\EdarateShahri;
use App\Models\Contractor;

class RoadObservationController extends Controller
{
    // public function index(Request $request)
    // {
    //     $province = $request->province;
    //     $city = $request->city;
    //     $fromDate = $request->start_date ?? "2021-03-21";
    //     $toDate = $request->end_date ?? \Carbon\Carbon::now()->format('Y-m-d');


    //     if (Auth::user()->hasRole('superadmin') || Auth::user()->hasRole('management') || Auth::user()->hasRole('office')) {
    //         $problems = RoadObserved::select('id', 'AutoID as uid', 'Title', 'StartTime_DateTime', 'EndTime_DateTime', 'ProvinceName', 'rms_province_id as ProvinceID', 'TownName', 'lng', 'lat', 'EventTypeTitle', 'FeatureTypeTitle', 'rms_status', 'rms_start_latlng', 'rms_description', DB::raw('IFNULL(Description, "-") as Description'), DB::raw('IFNULL(MobileForSendEventSms, "-") as MobileForSendEventSms'), DB::raw('IF(rms_status <> 0, rms_last_activity_fa, "") as rms_last_activity'))
    //         ->with('files')
    //         ->when($province, function ($query, $province) {
    //             return $query->where('rms_province_id', $province);
    //         })
    //         ->when($city, function ($query, $city) {
    //             return $query->where('rms_city_id', $city);
    //         })
    //         ->when($fromDate, function ($query) use ($fromDate, $toDate) {
    //             return $query->whereBetween('created_at', [$fromDate." 00:00:00", $toDate." 23:59:59"]);
    //         })
    //         ->get();
    //     } elseif (Auth::user()->hasRole('shahrestan')) {
    //         $problems = RoadObserved::select('id', 'AutoID as uid', 'Title', 'StartTime_DateTime', 'EndTime_DateTime', 'ProvinceName', 'rms_province_id as ProvinceID', 'TownName', 'lng', 'lat', 'EventTypeTitle', 'FeatureTypeTitle', 'rms_status', 'rms_start_latlng', 'rms_description', DB::raw('IFNULL(Description, "-") as Description'), DB::raw('IFNULL(MobileForSendEventSms, "-") as MobileForSendEventSms'), DB::raw('IF(rms_status <> 0, rms_last_activity_fa, "") as rms_last_activity'))
    //         ->where('rms_city_id', Auth::user()->city_id)
    //         ->with('files')
    //         ->when($province, function ($query, $province) {
    //             return $query->where('rms_province_id', $province);
    //         })
    //         ->when($city, function ($query, $city) {
    //             return $query->where('rms_city_id', $city);
    //         })
    //         ->when($fromDate, function ($query) use ($fromDate, $toDate) {
    //             return $query->whereBetween('created_at', [$fromDate." 00:00:00", $toDate." 23:59:59"]);
    //         })
    //         ->get();
    //     } elseif (Auth::user()->hasRole('setadi') || Auth::user()->hasRole('shahrestan-edarat')) {
    //         $problems = RoadObserved::select('id', 'AutoID as uid', 'Title', 'StartTime_DateTime', 'EndTime_DateTime', 'ProvinceName', 'rms_province_id as ProvinceID', 'TownName', 'lng', 'lat', 'EventTypeTitle', 'FeatureTypeTitle', 'rms_status', 'rms_start_latlng', 'rms_description', DB::raw('IFNULL(Description, "-") as Description'), DB::raw('IFNULL(MobileForSendEventSms, "-") as MobileForSendEventSms'), DB::raw('IF(rms_status <> 0, rms_last_activity_fa, "") as rms_last_activity'))
    //         ->where('rms_province_id', Auth::user()->province_id)
    //         ->with('files')
    //         ->when($province, function ($query, $province) {
    //             return $query->where('rms_province_id', $province);
    //         })
    //         // ->when($city, function($query, $city) {
    //         //     return $query->where('rms_city_id', $city);
    //         // })
    //         ->when($fromDate, function ($query) use ($fromDate, $toDate) {
    //             return $query->whereBetween('created_at', [$fromDate." 00:00:00", $toDate." 23:59:59"]);
    //         })
    //         ->get();
    //     }



    //     // $roadProblemsCode = [
    //     //     1 => 'چاله و ناهمواری در سطح راه',
    //     //     2 => 'پاکسازی سطح راه (لاشه حیوان)',
    //     //     3 => 'پاکسازی سطح راه (جسم خارجی)',
    //     //     4 => 'پاکسازی سطح راه (سنگریزه)',
    //     //     5 => 'پاکسازی سطح راه (گازوئیل و مواد روغنی)',
    //     //     6 => 'ایمن‌سازی حفاط‌ها و علائم آسیب‌دیده و ناایمن'
    //     // ];

    //     return response()->json([
    //         'status' => 'succeed',
    //         'message' => '',
    //         'data' => $problems
    //     ], 200);
    // }

    public function indexPublic()
    {
        $problems = RoadObserved::with('files')->get();

        $roadProblems = [];

        foreach ($problems as $key => $problem) {
            $roadProblems[$key] = [
                'id' => $problem->id,
                'uid' => $problem->AutoID,
                'Title' => $problem->Title ?? null,
                'StartTime_DateTime' => verta($problem->StartTime_DateTime)->format('Y/n/j - H:i'),
                'EndTime_DateTime' => verta($problem->EndTime_DateTime)->format('Y/n/j - H:i'),
                'ProvinceName' => $problem->ProvinceName ?? null,
                'ProvinceID' => $problem->rms_province_id ?? null,
                'TownName' => $problem->TownName ?? null,
                'lng'=> $problem->lng ?? null,
                'lat'=> $problem->lat ?? null,
                'EventTypeTitle' => $problem->EventTypeTitle ?? null,
                'FeatureTypeTitle' => $problem->FeatureTypeTitle ?? null,
                'Description' => $problem->Description ?? '-',
                'MobileForSendEventSms' => $problem->MobileForSendEventSms ?? '-',
                'rms_status' => $problem->rms_status,
                'rms_start_latlng' => $problem->rms_start_latlng ?? null,
                'rms_description' => $problem->rms_description ?? null,
                'rms_last_activity' => ($problem->rms_status > 0) ? verta($problem->updated_at)->format('Y/n/j - H:i') : null,
                'files' => $problem->files
            ];
        }

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadProblems
        ], 200);
    }


    public function update(Request $request, $id)
    {
        // dd($request->input('rms-description'));
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1037);
        }
        $roadProblem = RoadObserved::find($id);

        $files_path = [];
        $file_index = 0;
        $file_time = time();
        $uuid = \Uuid::generate();
        if ($request->file('image-before-1')) {
            $roadProblem->files()->where('path', 'like', '%_image-before-1_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-before-1')->storeAs(
                'public/road_observeds',
                'img4_' . $file_time . '_image-before-1_' . $roadProblem->id . '_' . $uuid.'.'. $request->file('image-before-1')->extension()
            );
            $file_index++;
            $roadProblem->image_before = 'storage/road_observeds/'.'img4_' . $file_time . '_image-before-1_' . $roadProblem->id . '_' . $uuid.'.'. $request->file('image-before-1')->extension();
        }

        if ($request->file('image-after-1')) {
            $roadProblem->files()->where('path', 'like', '%_image-after-1_%')->delete();

            $files_path[$file_index]['path'] = $request->file('image-after-1')->storeAs(
                'public/road_observeds',
                'img4_' . $file_time . '_image-after-1_' . $roadProblem->id . '_' . $uuid.'.'. $request->file('image-after-1')->extension()
            );
            $file_index++;
            $roadProblem->image_after = 'storage/road_observeds/'.'img4_' . $file_time . '_image-after-1_' . $roadProblem->id . '_' . $uuid.'.'.$request->file('image-after-1')->extension();
        }

        ///////  milad i uncomment this
        $files =  json_encode($files_path);
        $roadProblem->problemHistories()->create([
            'user_id' => Auth::user()->id, //$request->user()->id,// 470
            'previous_rms_status' => $roadProblem->rms_status,
            'previous_rms_start_latlng' => $roadProblem->rms_start_latlng,
            'previous_rms_end_latlng' => $roadProblem->rms_end_latlng,
            'previous_rms_description' => $roadProblem->rms_description,
            'new_files' => $files
        ]);

        $roadProblem->rms_status = $request->input('rms-status') ?? $roadProblem->rms_status;
        if ($request->input('rms-start-latlng')) {
            $roadProblem->rms_start_latlng = explode(',', $request->input('rms-start-latlng')) ?? null;
        }
        if ($request->input('rms-end-latlng')) {
            $roadProblem->rms_end_latlng = explode(',', $request->input('rms-end-latlng')) ?? null;
        }
        $roadProblem->rms_description = $request->input('rms-description') ?? $roadProblem->rms_description;

        $now_date_time = Carbon::now();
        $roadProblem->updated_at_fa = Verta::instance($now_date_time);

        $roadProblem->rms_last_activity_fa = Verta::instance($now_date_time);
        $roadProblem->rms_last_activity = $now_date_time;

        $roadProblem->save();

        // if ($file_index > 0) {
        //     $roadProblem->files()->createMany($files_path);
        // }
        $url = "https://riws.rmto.ir/WebServices/NRPTrafficStatus.asmx?wsdl";
        try {
            $array = array('strUserName' => 'vaytelrop',
                               'strPassword' => 'VaYtelROP*2024',
                               'strAutoID' => $roadProblem->fk_RegisteredEventMessage,
                               'strStateID' => ($request->input('rms-status') == 1) ? '2' : '3',
                               'strDescription' =>  $request->input('rms-description') ?? $roadProblem->rms_description,
                               'strPreviousImageLink' => "https://rms.rmto.ir/".$files,
                               'strNextImageLink' => "https://rms.rmto.ir/".$files,
                               'strRMSDateAndTime' => $roadProblem->updated_at
                          );
            $soap_client = new SoapClient($url);
            $result = $soap_client->UpdateInfo_RoadObservedProblems($array);
        } catch (SoapFault $e) {
            echo $e->getMessage();
            $msg = 'rms: error in get road observation webservice babe!!!!'."\n";
            $msg .= $e->getMessage();
            echo "error in send to nikarayan at".date("Y-m-d H:i:s")."\n".$msg;
        }
        ///// sms send

        Auth::user()->addActivity("گزارش واکنش سریع با آیدی {$id} بروزرسانی شد.");

        return response()->json([
            'status' => 'succeed',
            'message' => 1,
            'data' => $roadProblem,
            'nikarayan_res' => $result
        ], 201);
    }

    public function getRoadObservedPreview($id, $op = 'print')
    {
        $roadProblem = RoadObserved::find($id);

        $filesArray = [
            0 => '/var/www/rms/storage/app/public/no-img-placeholder.png',
            1 => '/var/www/rms/storage/app/public/no-img-placeholder.png',
            // 2 => '/var/www/rms/storage/app/public/no-img-placeholder.png',
            // 3 => '/var/www/rms/storage/app/public/no-img-placeholder.png'
        ];

        foreach ($roadProblem->files as $image) {
            $filesArray[0] = 'https://rms.rmto.ir/'.$roadProblem->image_before;
            $filesArray[1] = 'https://rms.rmto.ir/'.$roadProblem->image_after;
        }

        $roadProblemArray = [
            'province_name' => $roadProblem->ProvinceName,
            'city_name' => $roadProblem->TownName,
            'title' => $roadProblem->Title,
            'type' => $roadProblem->EventTypeTitle,
            'description' => $roadProblem->Description,
            'lat_lng' => [
                $roadProblem->lat,
                $roadProblem->lng
            ],
            'mobile' => $roadProblem->MobileForSendEventSms,
            'date' => $roadProblem->StartTime_DateTime_fa,
            'images' => $filesArray,
            'rms_description' => $roadProblem->rms_description,
            'rms_start_latlng' => $roadProblem->rms_start_latlng,
            'rms_end_latlng' => $roadProblem->rms_end_latlng,
            'rms_last_activity' =>  $roadProblem->rms_last_activity_fa ?? null
        ];

        if ($op == 'print') {
            $pdf = SnappyPdf::loadView('rmto-preview.pages.fast-reaction-preview', ['roadProblemArray' => $roadProblemArray]);
            return $pdf->download('fast-reaction-' . $roadProblem->id . '.pdf');
        } else {
            // return response()->json([
            //     'status' => 'succeed',
            //     'message' => '',
            //     'data' => $roadProblemArray
            // ], 200);
        }
    }

    public function getRoadObservedCount()
    {
        $start_year = explode('-', verta()->startYear()->format('Y-m-d')); // 1396-01-01 00:00:00
        $start_year = Verta::getGregorian($start_year[0], $start_year[1], $start_year[2]);
        $end_year = explode('-', verta()->endYear()->format('Y-m-d')); // 1396-12-29 23:59:59
        $end_year = Verta::getGregorian($end_year[0], $end_year[1], $end_year[2]);
        $date_from = new \DateTime();
        $date_from = $date_from->format('Y-m-d');
        if (Auth::user()->hasRole('superadmin')) {
            $problems = RoadObserved::where('rms_status', 0)
                ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                $date_from." 23:59:59"])
                ->count();
            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $problems
            ], 200);
        } else {
            if (Auth::user()->city_id != null) {
                $problems = RoadObserved::where('rms_province_id', Auth::user()->province_id)
                    ->where('rms_city_id', Auth::user()->city_id)
                    ->where('rms_status', 0)
                    ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                  $date_from." 23:59:59"])
                    ->count();
            } elseif (Auth::user()->province_id != null) {
                $problems = RoadObserved::where('rms_province_id', Auth::user()->province_id)
                    ->where('rms_status', 0)
                    ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                    $date_from." 23:59:59"])
                    ->count();
            } else {
                $problems = 0;
            }

            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $problems
            ], 200);
        }
    }

    public function fwd_city(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1037);
        }
        // return $request;
        $data = RoadObserved::find($request->id);
        // dd($data);
        $data->rms_city_id = $request->city_id;
        $data->TownName = $request->city_fa;
        $data->rms_status = 0;
        $data->save();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => ''
        ], 200);
    }

    public function statics()
    {
        // Verta::getGregorian()->format('Y-n-j'); // [2015,12,25]
        $start_week = explode('-', verta()->startWeek()->format('Y-m-d'));
        $start_week = Verta::getGregorian($start_week[0], $start_week[1], $start_week[2]);
        $end_week  = explode('-', verta()->endWeek()->format('Y-m-d')); // 1396-04-30 23:59:59
        $end_week = Verta::getGregorian($end_week[0], $end_week[1], $end_week[2]);
        $start_month = explode('-', verta()->startMonth()->format('Y-m-d')); // 1396-04-01 00:00:00
        $start_month = Verta::getGregorian($start_month[0], $start_month[1], $start_month[2]);
        $end_month = explode('-', verta()->endMonth()->format('Y-m-d')); // 1396-04-31 00:00:00
        $end_month = Verta::getGregorian($end_month[0], $end_month[1], $end_month[2]);
        $start_year = explode('-', verta()->startYear()->format('Y-m-d')); // 1396-01-01 00:00:00
        $start_year = Verta::getGregorian($start_year[0], $start_year[1], $start_year[2]);
        $end_year = explode('-', verta()->endYear()->format('Y-m-d')); // 1396-12-29 23:59:59
        $end_year = Verta::getGregorian($end_year[0], $end_year[1], $end_year[2]);
        // $data = array($start_week, $end_week, $start_month, $end_month, $start_year, $end_year);
        // dd($data);
        // return $end_year;
        $date_to_day = new \DateTime('tomorrow');
        $date_to_day = $date_to_day->format('Y-m-d');
        $date_from = new \DateTime();
        $date_from = $date_from->format('Y-m-d');
        $date_from_7days = date("Y-m-d", strtotime("-7 day"));
        $date_from_30days = date("Y-m-d", strtotime("-30 day"));
        $day = RoadObserved::whereBetween('created_at', [$date_from." 00:00:00",
                                $date_to_day." 23:59:59"])
                                ->count();
        $weak = RoadObserved::whereBetween('created_at', [$start_week[0]."-".$start_week[1]."-".$start_week[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $month = RoadObserved::whereBetween('created_at', [$start_month[0]."-".$start_month[1]."-".$start_month[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $year = RoadObserved::whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $day_ok = RoadObserved::whereBetween('created_at', [$date_from." 00:00:00",
                                $date_to_day." 23:59:59"])
                                ->where('rms_status', '<>', 0)
                                ->count();
        $weak_ok = RoadObserved::whereBetween('created_at', [$start_week[0]."-".$start_week[1]."-".$start_week[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->where('rms_status', '<>', 0)
                                ->count();
        $month_ok = RoadObserved::whereBetween('created_at', [$start_month[0]."-".$start_month[1]."-".$start_month[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->where('rms_status', '<>', 0)
                                ->count();
        $year_ok = RoadObserved::whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->where('rms_status', '<>', 0)
                                ->count();
        // $day = DB::select(DB::raw(""));
        return response()->json([
            'all' =>[
            'today' => $day,
            'week'  => $weak,
            'month' => $month,
            'year'  =>$year
            ],
            'chart' => [
                'today'=> [
                'today_done'=>$day_ok,
                'today_not_done' =>$day-$day_ok
                ],
                'weak'=> [
                'weak_done'=>$weak_ok,
                'weak_not_done' =>$weak-$weak_ok
                ],
                'month'=> [
                'month_done'=>$month_ok,
                'month_not_done' =>$month-$month_ok
                ],
                'year'=> [
                'year_done'=>$year_ok,
                'year_not_done' =>$year-$year_ok
                ],
            ]
        ]);
    }

    public function project_done(Request $request)
    {
        $from_date = new \DateTime();
        $from_date = $from_date->format('Y-m-d');

        $date_from = $request->from_date ?? null;
        $date_to   = $request->to_date ?? null;
        $province_id = $request->province ?? null;
        $rms_status = $request->rms_status ?? null;
        $feature_type = $request->subject ?? null;

        $time_start = microtime(true);
        $userCity = Auth::user()->city_id;
        $userProvince = Auth::user()->province_id;

        if (Auth::user()->hasRole('superadmin') || Auth::user()->hasRole('management') || Auth::user()->hasRole('office')) {
            $date_from = '2020-07-13';
            $date_to = new \DateTime();
            $date_to = $date_to->format('Y-m-d');
            $date_from = $request->from_date ?? $date_from;
            $date_to   = $request->to_date ?? $date_to;

            $data = \App\Models\RoadObserved::select('road_observeds.id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'road_observeds.lat as h', 'road_observeds.lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e', 'rms_description as n', 'rms_status as l', 'rms_start_latlng as m', 'rms_last_activity_fa as o')
                                            ->where('rms_status', '<>', 0)
                                            ->when(($date_from && $date_to), function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($province_id, function ($query, $province_id) {
                                                return $query->where('rms_province_id', $province_id);
                                            })
                                            ->when($rms_status, function ($query, $rms_status) {
                                                return $query->where('rms_status', $rms_status);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as p, CONCAT('https://rms.rmto.ir/', image_after) as q")
                                            ->orderBy('id', 'DESC')
                                            ->get();
        } elseif (Auth::user()->hasRole('shahrestan')) {
            $data = \App\Models\RoadObserved::select('road_observeds.id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'road_observeds.lat as h', 'road_observeds.lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e', 'rms_description as n', 'rms_status as l', 'rms_start_latlng as m', 'rms_last_activity_fa as o')
                                            ->where('rms_status', '<>', 0)
                                            ->where('rms_city_id', $userCity)
                                            ->when(($date_from && $date_to), function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($rms_status, function ($query, $rms_status) {
                                                return $query->where('rms_status', $rms_status);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as p, CONCAT('https://rms.rmto.ir/', image_after) as q")
                                            ->orderBy('id', 'DESC')
                                            ->get();
        } elseif (Auth::user()->hasRole('setadi') || Auth::user()->hasRole('shahrestan-edarat')) {
            $data = \App\Models\RoadObserved::select('road_observeds.id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'road_observeds.lat as h', 'road_observeds.lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e', 'rms_description as n', 'rms_status as l', 'rms_start_latlng as m', 'rms_last_activity_fa as o')
                                            ->where('rms_status', '<>', 0)
                                            ->where('rms_province_id', $userProvince)
                                            ->when(($date_from && $date_to), function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($rms_status, function ($query, $rms_status) {
                                                return $query->where('rms_status', $rms_status);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as p, CONCAT('https://rms.rmto.ir/', image_after) as q")
                                            ->orderBy('id', 'DESC')
                                            ->get();
        } else {
            $data = \App\Models\RoadObserved::select('road_observeds.id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'road_observeds.lat as h', 'road_observeds.lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e', 'rms_description as n', 'rms_status as l', 'rms_start_latlng as m', 'rms_last_activity_fa as o')
                                            ->where('rms_status', '<>', 0)
                                            ->where('rms_province_id', $userProvince)
                                            ->when(($date_from && $date_to), function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($rms_status, function ($query, $rms_status) {
                                                return $query->where('rms_status', $rms_status);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as p, CONCAT('https://rms.rmto.ir/', image_after) as q")
                                            ->orderBy('id', 'DESC')
                                            ->get();
        }

        $time_end = microtime(true);
        $execution_time = ($time_end - $time_start);
        // echo '<b>Total Execution Time:</b> '.$execution_time;
        $info = array();
        $info = [
            'a' => 'road_observeds_id',
            'b' => 'title' ,
            'c' => 'StartTime_DateTime_fa',
            'd' => 'ProvinceName' ,
            'e' => 'rms_province_id' ,
            'f' => 'TownName' ,
            'g' => 'road_observeds_lng' ,
            'h' => 'road_observeds_lat' ,
            'i' => 'FeatureTypeTitle' ,
            'j' => 'Description' ,
            'k' => 'MobileForSendEventSms' ,
            'l' => 'rms_status',
            'm' => 'rms_start_latlng',
            'n' => 'rms_description',
            'o' => 'rms_last_activity_fa' ,
            'p' => 'before',
            'q' => 'after',
        ];
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
            'info' =>$info
        ], 200);
    }


    public function project_pending(Request $request)
    {
        $date_from = $request->from_date ?? null;
        $date_to   = $request->to_date ?? null;

        $userProvince = Auth::user()->province_id;
        $userCity = Auth::user()->city_id;
        $date = \Carbon\Carbon::today()->subDays(7);
        $feature_type = $request->subject ?? null;
        
        // if($request->develop){
        //     dd(auth()->user()->roles->pluck('name'));
        // }

        if (Auth::user()->hasRole('superadmin') || Auth::user()->hasRole('management') || Auth::user()->hasRole('office')) {
            // $from_date = new \DateTime();
            // $from_date = $from_date->format('Y-m-d');
            $date_from = $request->from_date ?? null;
            $date_to   = $request->to_date ?? null;

            $province = $request->province ?? null;
            $data = \App\Models\RoadObserved::select('id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'lat as h', 'lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e')
                                            ->where('rms_status', 0)
                                            ->when($date_from, function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($province, function ($query, $province) {
                                                return $query->where('rms_province_id', $province);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->orderBy('id', 'DESC')
                                            ->get();
        } elseif (Auth::user()->hasRole('shahrestan')) {
            $data = \App\Models\RoadObserved::select('id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'lat as h', 'lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e')
                                            ->where('rms_status', 0)
                                            ->where('rms_city_id', $userCity)
                                            ->when($date_from, function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->orderBy('id', 'DESC')
                                            ->get();

            if($request->develop){
                dd('ss', $data[0]);
            }
        } elseif (Auth::user()->hasRole('setadi') || Auth::user()->hasRole('shahrestan-edarat')) {
            $data = \App\Models\RoadObserved::select('id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'lat as h', 'lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e')
                                            ->where('rms_status', 0)
                                            ->when($date_from, function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->where('rms_province_id', $userProvince)
                                            ->orderBy('id', 'DESC')
                                            ->get();
        } else {
            $data = \App\Models\RoadObserved::select('id as a', 'title as b', 'StartTime_DateTime_fa as c', 'ProvinceName as d', 'TownName as f', 'lat as h', 'lng as g', 'FeatureTypeTitle as i', 'Description as j', 'MobileForSendEventSms as k', 'rms_province_id as e')
                                            ->where('rms_status', 0)
                                            ->when($date_from, function ($query) use ($date_from, $date_to) {
                                                return $query->whereBetween('created_at', [$date_from." 00:00:00", $date_to." 23:59:59"]);
                                            })
                                            ->when($feature_type, function ($query, $feature_type) {
                                                return $query->where('fk_FeatureType', $feature_type);
                                            })
                                            ->where('rms_province_id', $userProvince)
                                            ->orderBy('id', 'DESC')
                                            ->get();
        }



        $done_cnt = \App\Models\RoadObserved::where('rms_status', '!=', 0)->count();

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'cnt_done' => $done_cnt,
            'data' => $data,
        ], 200);
    }


    /**
     * Amirreza's refactor
     */

    public function indexDevelop(Request $request)
    {
        $date = \Carbon\Carbon::today()->subDays(7);

        // Query parameters
        $province = $request->province;
        $city = $request->city;
        $fromDate = $request->from_date;
        $toDate = $request->to_date ?? \Carbon\Carbon::now();
        $status = $request->status;

        $problems = RoadObserved::with('files')
                                ->where('created_at', '>', $date)
                                ->when($province, function ($query, $province) {
                                    return $query->where('rms_province_id', $province);
                                })
                                ->when($city, function ($query, $city) {
                                    return $query->where('rms_city_id', $city);
                                })
                                ->when($fromDate, function ($query) use ($fromDate, $toDate) {
                                    return $query->whereBetween('created_at', [$fromDate, $toDate]);
                                })
                                ->when($status, function ($query, $status) {
                                    return $query->where('rms_status', '!=', 0);
                                })
                                ->get();

        return response()->json([
            'message' => 'success',
            'data' => $problems
        ]);
    }

    public function referralToOtherCities(Request $request)
    {
        if (! $request->id || ! $request->city_id) {
            return response()->json([
                'status' => 'error',
                'message' => 'لطفا تمامی‌ فیلد‌ها را وارد کنید.'
            ], 400);
        }

        $roadObserved = RoadObserved::find($request->id);
        $roadObserved->rms_city_id = $request->city_id;
        $city_fa = City::where('id', $request->city_id)->first()->name_fa;
        $roadObserved->TownName = $city_fa;
        $roadObserved->rms_status = 0;

        /// TODO: add log

        $roadObserved->save();

        return response()->json([
            'status' => 'success',
            'message' => "شکایت «{$roadObserved->Title}» با موفقیت به شهرستان «{$city_fa}» ارجاع داده شد."
        ], 200);
    }

    public function roadObservedCounts(Request $request)
    {
        $start = microtime(true);

        $start_year = explode('-', verta()->startYear()->format('Y-m-d')); // 1396-01-01 00:00:00
        $start_year = Verta::getGregorian($start_year[0], $start_year[1], $start_year[2]);
        $end_year = explode('-', verta()->endYear()->format('Y-m-d')); // 1396-12-29 23:59:59
        $end_year = Verta::getGregorian($end_year[0], $end_year[1], $end_year[2]);
        $date_from = new \DateTime();
        $date_from = $date_from->format('Y-m-d');

        if (Auth::user()->hasRole('superadmin')) {
            $handledCount = RoadObserved::where('rms_status', '!=', 0)
                                        ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                            $date_from." 23:59:59"])
                                        ->count();
            $pendingCount = RoadObserved::where('rms_status', 0)
                                        ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                            $date_from." 23:59:59"])
                                        ->count();
        } else {
            if (Auth::user()->province_id != null) {
                $handledCount = RoadObserved::where('rms_status', '!=', 0)
                                            ->where('rms_province_id', Auth::user()->province_id)
                                            ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                                            $date_from." 23:59:59"])
                                            ->count();
                $pendingCount = RoadObserved::where('rms_status', 0)
                                            ->where('rms_province_id', Auth::user()->province_id)
                                            ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                $date_from." 23:59:59"])
                                            ->count();
            } elseif (Auth::user()->city_id != null) {
                $handledCount = RoadObserved::where('rms_status', '!=', 0)
                                            ->where('rms_city_id', Auth::user()->province_id)
                                            ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                $date_from." 23:59:59"])
                                            ->count();
                $pendingCount = RoadObserved::where('rms_status', 0)
                                            ->where('rms_city_id', Auth::user()->province_id)
                                            ->whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                $date_from." 23:59:59"])
                                            ->count();
            }
        }

        return response()->json([
            'status' => 'success',
            'data' => [
                'pending' => $pendingCount,
                'handled' => $handledCount
            ]
        ]);
    }

    // --------------------------------------------------------------------------------------
    // Hamid
    //

    // public function indexView()
    // {
    //     if (! auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
    //         abort(403);
    //     }
    //     return view('rmto-preview.pages.road_observation');
    // }

    // public function count()
    // {
    //     if (! auth()->user()->permissions()->where('type', 'fastreact')->exists()) {
    //         abort(403);
    //     }

    //     $from_date_array = explode('-', verta()->startYear()->format('Y-m-d'));
    //     $from_datetime = implode('-', verta()->getGregorian($from_date_array[0], $from_date_array[1], $from_date_array[2])) . ' 00:00:00';
    //     $to_datetime = Carbon::now()->toDateString() . ' 23:59:59';

    //     if (auth()->user()->hasPermissionTo('show-fast-react')) {
    //         $data = RoadObserved::whereBetween('created_at', [$from_datetime, $to_datetime])
    //                             ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
    //                                          sum(case when rms_status != 0 then 1 else 0 end) as done')
    //                             ->get();
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
    //         if (!auth()->user()->province_id) {
    //             return response()->json([
    //                 'message' => 'استانی برای شما در سامانه مشخص نشده است!'
    //             ], 400);
    //         }

    //         $data = RoadObserved::where('rms_province_id', Auth::user()->province_id)
    //                         ->whereBetween('created_at', [$from_datetime, $to_datetime])
    //                         ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
    //                                      sum(case when rms_status != 0 then 1 else 0 end) as done')
    //                         ->get();
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-city')) {
    //         if (!auth()->user()->city_id) {
    //             return response()->json([
    //                 'message' => 'شهری برای شما در سامانه مشخص نشده است!'
    //             ], 400);
    //         }

    //         $data = RoadObserved::where('rms_city_id', Auth::user()->city_id)
    //                         ->whereBetween('created_at', [$from_datetime, $to_datetime])
    //                         ->selectRaw('sum(case when rms_status = 0 then 1 else 0 end) as pending,
    //                                      sum(case when rms_status != 0 then 1 else 0 end) as done')
    //                         ->get();
    //     }

    //     return response()->json([
    //         'status' => 'succuss',
    //         'data' => $data
    //     ]);
    // }

    // public function showPending(Request $request)
    // {
    //     if (! auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
    //         abort(403);
    //     }

    //     $fields = ['AutoID', 'road_observeds.id', 'Title', 'road_observeds.created_at', 'lat', 'lng',
    //     'FeatureTypeTitle', 'Description', 'MobileForSendEventSms', 'road_observeds.province_id','province_fa', 'city_fa', 'edarate_shahri.name_fa'];

    //     $aliases = ['', 'road_observeds_id', '', 'road_observeds_created_at', '', '', '', '', '', 'province_id', '', '', 'edarate_shahri_name_fa'];

    //     $selectRaw = makeSelectQuery($fields, $aliases);

    //     if (auth()->user()->hasPermissionTo('show-fast-react')) {
    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                              ->where('rms_status', 0)
    //                              ->whereNotNull('edarate_shahri_id')
    //                              ->selectRaw($selectRaw);
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
    //         if (is_null(auth()->user()->province_id)) {
    //             return response()->json([
    //                 'message' => 'استانی برای شما در سامانه ثبت نشده است!'
    //             ], 400);
    //         }

    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                              ->where('rms_status', 0)
    //                              ->whereNotNull('edarate_shahri_id')
    //                              ->where('rms_province_id', auth()->user()->province_id)
    //                              ->selectRaw($selectRaw);
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-edarate-shahri')) {
    //         if (is_null(auth()->user()->edarate_shahri_id)) {
    //             return response()->json([
    //                 'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
    //             ], 400);
    //         }

    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                              ->where('rms_status', 0)
    //                              ->whereNotNull('edarate_shahri_id')
    //                              ->where('edarate_shahri_id', auth()->user()->edarate_shahri_id)
    //                              ->selectRaw($selectRaw);
    //     }

    //     $data = processDataTable($request, '', $fields, $query);
    //     // auth()->user()->addActivityComplete(1117);
    //     return response()->json(
    //         $data,
    //         $data['status'],
    //     );
    // }

    // public function showDone(Request $request)
    // {
    //     if (! auth()->user()->hasAnyPermission(['show-fast-react-edarate-shahri', 'show-fast-react-province', 'show-fast-react'])) {
    //         abort(403);
    //     }

    //     $fields = ['AutoID', 'road_observeds.id', 'Title', 'road_observeds.created_at', 'lat', 'lng',
    //                'FeatureTypeTitle', 'Description', 'MobileForSendEventSms',
    //                'rms_description','rms_status','rms_start_latlng','rms_last_activity_fa', 'road_observeds.province_id', 'province_fa', 'city_fa', 'edarate_shahri.name_fa'];

    //     $aliases = ['', 'road_observeds_id', '', 'road_observeds_created_at', '', '', '', '', '', '', '', '', '', 'province_id', '', '', 'edarate_shahri_name_fa'];

    //     $selectRaw = makeSelectQuery($fields, $aliases);

    //     if (auth()->user()->hasPermissionTo('show-fast-react')) {
    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                             ->where('rms_status', '!=', 0)
    //                             ->selectRaw($selectRaw)
    //                             ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-province')) {
    //         if (is_null(auth()->user()->province_id)) {
    //             return response()->json([
    //                 'message' => 'استانی برای شما در سامانه ثبت نشده است!'
    //             ], 400);
    //         }

    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                             ->where('rms_province_id', auth()->user()->province_id)
    //                             ->where('rms_status', '!=', 0)
    //                             ->selectRaw($selectRaw)
    //                             ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
    //     } elseif (auth()->user()->hasPermissionTo('show-fast-react-edarate-shahri')) {
    //         if (is_null(auth()->user()->edarate_shahri_id)) {
    //             return response()->json([
    //                 'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
    //             ], 400);
    //         }

    //         $query = RoadObserved::leftjoin('edarate_shahri', 'road_observeds.edarate_shahri_id', 'edarate_shahri.id')
    //                             ->where('edarate_shahri_id', auth()->user()->edarate_shahri_id)
    //                             ->where('rms_status', '!=', 0)
    //                             ->selectRaw($selectRaw)
    //                             ->selectRaw("CONCAT('https://rms.rmto.ir/',image_before) as image_before, CONCAT('https://rms.rmto.ir/', image_after) as image_after");
    //     }

    //     $data = processDataTable($request, '', $fields, $query);
    //     return response()->json(
    //         $data,
    //         200
    //     );
    // }

    // public function referList(int $id)
    // {
    //     $edarat_shahri = EdarateShahri::where('province_id', $id)->select('id', 'name_fa', 'province_id')->get();
    //     // $contractors = Contractor::where('province_id', $id)->select('id', 'name', 'province_id')->get();

    //     return response()->json([
    //         'status' => 200,
    //         'data' => $edarat_shahri,
    //     ]);
    // }

    // public function refer(Request $request, RoadObserved $roadObserved)
    // {
    //     $request->validate([
    //         'edarate_shahri_id' => 'required|numeric',
    //         'refer_description' => 'required|string',
    //     ]);

    //     if ($roadObserved->rms_status != 0) {
    //         return response()->json([
    //             'message' => 'access to requested resource is forbidden.'
    //         ], 403);
    //     }

    //     auth()->user()->addActivityComplete(1037);
    //     $roadObserved->update([
    //         'edarate_shahri_id' => $request->edarate_shahri_id,
    //     ]);

    //     RoadObservationHistory::create([
    //         'id' => $roadObserved->id,
    //         'user_id' => auth()->user()->id,
    //         'action' => 'refer',
    //         'description' => $request->refer_description,
    //     ]);

    //     return response()->json([
    //         'status' => 'succeed',
    //         'message' => '',
    //         'data' => $roadObserved
    //     ], 200);
    // }

    // public function restore(Request $request, RoadObserved $roadObserved)
    // {
    //     if (! auth()->user()->hasPermissionTo('restore-fast-react')) {
    //         abort(403);
    //     }

    //     $request->validate([
    //         'restore_description' => 'required|string',
    //     ]);

    //     if ($roadObserved->image_before) {
    //         $before_path = explode('/', $roadObserved->image_before);
    //         Storage::delete('public/'. implode('/', array_slice($before_path, 1)));
    //     }

    //     if ($roadObserved->image_after) {
    //         $after_path = explode('/', $roadObserved->image_after);
    //         Storage::delete('public/'. implode('/', array_slice($after_path, 1)));
    //     }

    //     auth()->user()->addActivityComplete(1037);
    //     $roadObserved->update([
    //         'image_before' => null,
    //         'image_after' => null,
    //         'rms_last_activity' => null,
    //         'rms_last_activity_fa' => null,
    //         'updated_at_fa' => null,
    //         'updated_at' => null,
    //         'rms_status' => 0
    //     ]);

    //     RoadObservationHistory::create([
    //         'id' => $roadObserved->id,
    //         'user_id' => auth()->user()->id,
    //         'action' => 'restore',
    //         'description' => $request->restore_description,
    //     ]);

    //     return response()->json([
    //         'status' => 'succeed',
    //         'message' => '',
    //         'data' => $roadObserved
    //     ], 200);
    // }
}
