<?php

namespace App\Http\Controllers;

use App\Models\Coridor;
use App\Models\RoadPatrol;
use App\Models\RoutePath;
use App\Models\RoadItemsProject;
use App\Models\InfoItem;

use App\Services\NominatimService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Str;
use App\Models\RoadPatrolProject;
use App\Exports\AxisReport\AllSheet as AxisReportsSheets;
use Maatwebsite\Excel\Facades\Excel;

class CoridorsController extends Controller
{
    public function get_data(Request $request)
    {
        $latlng = $request->latlng;
        $type = $request->type;
        $myarray = array();
        array_push($myarray, $latlng[0]);
        $j = 0;
        for ($i = 0;$i<sizeof($latlng);$i++) {
            if (self::distance(floatval($myarray[$j][0])*10, floatval($myarray[$j][1])*10, floatval($latlng[$i][0])*10, floatval($latlng[$i][1])*10) < 2) {
                continue;
            } else {
                array_push($myarray, $latlng[$i]);
                $j++;
            }
        }
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 20; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        $id = $randomString;
        // dd($id);
        $data = $myarray;
        $dat = array();
        for ($i=0;$i<sizeof($data) - 1;$i++) {
            $x = $data[$i];
            $x[0][1] = $x[0][2];
            $x[0][2] = '.';
            $x[1][1] = $x[1][2];
            $x[1][2] = '.';
            array_push($dat, array('lat1'=>$x[0], 'lng1'=> $x[1], 'identifier' => $id));
        }
        RoutePath::insert($dat);//// insert
        $query = "select * from route_paths,coridors  where  (6371 * ACOS( COS( RADIANS(route_paths.lat1) ) * COS( RADIANS(coridors.lat) ) * COS( RADIANS(coridors.lng) - RADIANS(route_paths.lng1)) + SIN(RADIANS(route_paths.lat1)) * SIN(RADIANS(lat)) )    ) < 1  group by lat,lng";
        $result = DB::select($query);
        RoutePath::where('identifier', $id)->delete();//////  delete  table
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $result
        ], 200);
        return response()->json($result);
    }
    public function distance($lat1, $lon1, $lat2, $lon2)
    { ////// distance between two poings in lat and lng
        if (($lat1 == $lat2) && ($lon1 == $lon2)) {
            return 0;
        } else {
            $theta = $lon1 - $lon2;
            $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
            $dist = acos($dist);
            $dist = rad2deg($dist);
            $miles = $dist * 60 * 1.1515;
            return ($miles * 1.609344);
        }
    }
    public function index()
    {
        $allrecords = Coridor::all();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $allrecords
        ], 200);
    }
    public function store(Request $request)
    {
        //:::::::::::Maxter rz::::::::::::::
        $input = $request->all();
        $RecStore=Coridor::create($input);
        //:::::::::::::::::::::::::::::::::::
        $allrecords = Coridor::all();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $allrecords
        ], 200);
    }
    public function update(Request $request)
    {
        $request->validate([
        'id' => 'required|integer|exists:coridors,id'
        ]);
        $idd = $request->id;
        $validrecs = array_filter($request->all());
        $uprecords = Coridor::find($idd);
        $uprecords->fill($validrecs);
        $uprecords->save();
        $allrecords = Coridor::all();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $uprecords
        ], 200);
    }
    public function destroy(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:coridors,id'
            ]);
        $idd = $request->id;
       
        $delrec = Coridor::find($idd);
        $delrec->delete();
        $allrecords = Coridor::all();
        return response()->json([
             'status' => 'succeed',
             'message' => '',
             'data' => $allrecords
         ], 200);
    }
    public function get_coridor_10_report(Request $request)
    {
        $start_time = microtime(true);
        ///// developed by god milad babe
        /* $new_query = 'SELECT * FROM(SELECT st_distance(
            LINESTRING(POINT(32.469128717673335,51.99799060821534))
            ,POINT(road_items_projects.`start_lat`, road_items_projects.`start_lng`))* 111195
             AS ddd,start_lat,start_lng,id,province_id
             FROM road_items_projects )q ORDER BY ddd LIMIT 10'; */
        ///// developed by god milad babe
        ///// http vars
        $s_lat = $request->slat;
        $s_lng = $request->slng;
        $d_lat = $request->dlat;
        $d_lng = $request->dlng;
        $date_to = $request->dateto;
        $date_from = $request->datefrom;
        $item = $request->item ?? 0;
        $sub_item = $request->subitem ?? 0;
        ///// start
        $url = "https://testmap.141.ir/route/v1/driving/".$s_lng.",".$s_lat.";".$d_lng.",".$d_lat."?overview=full&alternatives=true&steps=true&annotations=true";
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        
        $result = file_get_contents($url, false, stream_context_create($arrContextOptions));
        return $result;
        
        
        dd($result);
        $result = json_decode($result);
        $geo = $result->routes[0]->geometry;
        // dd($geo);
        $points =  \GeometryLibrary\PolyUtil::decode($geo);
        // dd(count($points));
        // return;
        /////   with st_distance
        /*
        $new_query = 'SELECT * FROM(SELECT st_distance(LINESTRING(';
        foreach($points as $value){
            $new_query .= 'POINT('.$value['lat'].','.$value['lng'].'),';
        }
        $new_query = substr_replace($new_query ,"",-1);
        
        $new_query .= ')
            ,POINT(road_items_projects.`start_lat`, road_items_projects.`start_lng`))* 111195 AS ddd,start_lat,start_lng,id,province_id        FROM road_items_projects where province_id = 4)q';
        // dd($new_query);
        dd($new_query);
        $results = DB::select(DB::raw($new_query)); 
        */
        //// st_distance
        // $execution_time = ($end_time - $start_time);
        // echo " It takes ". $execution_time." seconds to execute the script";
        // dd($result);
        //coridor 1 name c1
        // $c1 = "https://testmap.141.ir/route/v1/driving/51.41126677393914,35.63613201722114;51.363811476621784,35.51441859244614;51.29825592041016,35.437736107595484;51.05895996093751,35.256833789618284;50.90515136718751,35.117100314572774;50.84279134869576,34.822139039454534;50.8800969,34.6423117;51.1083984375,34.459295756500175;51.28600627183915,34.16672512785317;56.26175746321679,27.220631942957304?overview=full&alternatives=true&steps=true&hints=jOsjgJnrI4AdAAAABAAAAFMAAAAAAAAAjAagQYHmAUCQmF1CAAAAAB0AAAAEAAAAUwAAAAAAAAC_AQAAMHkQA6fDHwJDeRADpMMfAgEArwARLKj6;hdQrgP___38oAAAApgAAAAAAAAAAAAAAMq5YQr7WJkMAAAAAAAAAACgAAACmAAAAAAAAAAAAAAC_AQAADsAPAxfoHQLjvw8DM-gdAgAArw0RLKj6;jn0VgP___38IAAAAMgAAANcEAAAmEQAAnTk3QR_NWUIR7s1EyYq2RQgAAAAyAAAA1wQAACYRAAC_AQAA2sQOA4e9HALQvw4DqLwcAhIAjwoRLKj6;u0QXgKWSNYCzAAAARQAAAPELAACwIQAAh4KiQxQd90J7s6xFzS1zRrMAAABFAAAA8QsAALAhAAC_AQAAfRILA5EuGgIQGQsDAvoZAg8ATwURLKj6;2NIYgJxSI4APAAAAoQAAAGwMAAB5BwAApdH4QdKQoEMQd8ZFsqpvRQ8AAAChAAAAbAwAAHkHAAC_AQAAVb8IA4LCFwI_wAgDLNgXAg4AvwURLKj6;ubUIgDHXIYBHAAAAEwMAADsBAAAAAAAAcdsOQ4kbxESVLR1EAAAAAEcAAAATAwAAOwEAAAAAAAC_AQAAzsoHA6JXEwKnzAcD-1cTAggAfwoRLKj6;OLMWgFpIN4AUAAAAKgAAAFwBAACLAAAAFPNnQWcf5UEko3JD-8fAQhQAAAAqAAAAXAEAAIsAAAC_AQAAgmAIA0eXEAJhXggDiJkQAgYATwMRLKj6;TGIbgDUNLYAzAAAAPAAAANQBAAA7AgAAakDzQpuDC0M8AYpELKGoRDMAAAA8AAAA1AEAADsCAAC_AQAAe9ILA5vIDQIu2gsDoM4NAggAjwgRLKj6;2Y5BgP___38AAAAAFwAAAKsFAAB8BQAAAAAAADCCF0HrZRdENlsSRAAAAAAXAAAAqwUAAHwFAAC_AQAAhYoOAxNMCQL2jw4DxVcJAgYAfxARLKj6;ddwfgP___38lAAAARgAAALAAAAAAAAAAz2B5QYVVVkHeDpJCAAAAACUAAABGAAAAsAAAAAAAAAC_AQAALHZaA8dWnwF9fFoDmFqfAQEAXxQRLKj6";
        // $c1 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;56.2781423,27.1793466?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;b-clgP5CM4AAAAAAIAAAAAAAAAApAAAAAAAAAEwMsUEAAAAAHfPiQQAAAAAgAAAAAAAAACkAAAC_AQAAsb1aA9W5ngF-vFoDU7meAQAAjwQRLKj6";
        // $c2 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;50.68046975880862,33.99455956454493;52.61859275400639,31.22061595984375;50.8458443,28.9310786?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;oE4QgKJOEIA6AAAAHwAAAAAAAAAAAAAArwIcQo2gpUEAAAAAAAAAADoAAAAfAAAAAAAAAAAAAAC_AQAAmVIFA6O2BgKWUgUDQLcGAgAA3xARLKj6;mtE1gP___38oAAAALgAAAOgBAAB2AQAAtHLEQhoCV0GxM5VEfetkRCgAAAAuAAAA6AEAAHYBAAC_AQAAvOoiA1lu3AFh5SIDiGPcAQUADwcRLKj6;VXEHgPanB4D2AwAAAAAAAMMCAAAAAAAA1gLTQwAAAAC7SJNDAAAAAPYDAAAAAAAAwwIAAAAAAAC_AQAALs4HA3F2uQGU2AcDB3S5AQQAfwIRLKj6";
        // $c3 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;49.689810276031494,34.10858889039525;48.1872669607401,30.452993606051912;48.27186584472657,30.37100539016938?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;BfoFgBP6BYA7AAAANgAAAAAAAAAAAAAAOnOFQkiQbEIAAAAAAAAAADsAAAA2AAAAAAAAAAAAAAC_AQAA1TT2At10CALSNPYCrXQIAgAA3wURLKj6;;n1AjgKFQI4DYAAAAtgAAAAAAAAAAAAAAjhQQQ0K88UIAAAAAAAAAANgAAAC2AAAAAAAAAAAAAAC_AQAAYZLgAn5szwH6keACvWzPAQAAPwIRLKj6";
        // $c4 = "https://testmap.141.ir/route/v1/driving/48.2591475,30.3636097;60.6470887,25.293269?overview=full&alternatives=true&steps=true&hints=R1AjgP___3-UAAAAAwEAAAAAAAAXAAAATkEkQ2rj9EIAAAAAY8zNQZQAAAADAQAAAAAAABcAAAC_AQAAOlvgAv1PzwFMYOAC2k_PAQAAHwARLKj6;ltBCgJjQQoBGAAAANgAAAAAAAAAAAAAAdEdEQu69E0IAAAAAAAAAAEYAAAA2AAAAAAAAAAAAAAC_AQAADGidA7jxgQGxZp0D1fGBAQAAnwsRLKj6";
        // $c5 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;48.94958496093751,35.14012515937234;45.5800155,34.515594?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;VYk2gP___39eAwAAaAMAAAAAAAC-CwAAtvrjRMgLpEEAAAAAwrPGRV4DAABoAwAAAAAAAL4LAAC_AQAAMNjqAhgHGAJR6eoCHTIYAgAADxIRLKj6;TBoQgEujMYADAAAALgAAADsAAAAvAAAA6W2BQAtJSkLQtYNCOApSQgMAAAAuAAAAOwAAAC8AAAC_AQAAWX63AhGpDgLwfrcCiqoOAgIAzwYRLKj6";
        // $c6 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;44.3876859,39.3886668?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;_VgUgCM0LoAKAQAATwAAAAAAAAAAAAAA6Iw5Q16rWkIAAAAAAAAAAAoBAABPAAAAAAAAAAAAAAC_AQAArE2lAjkEWQJmTaUC-wVZAgAAPwURLKj6";
        // $c7 = "https://testmap.141.ir/route/v1/driving/51.4013785,35.7006177;59.6059232,36.2974945?overview=full&alternatives=true&steps=true&hints=C9UogA3VKIAAAAAARQAAAAAAAAAAAAAAAAAAADdAN0IAAAAAAAAAAAAAAABFAAAAAAAAAAAAAAC_AQAAIlIQA7-_IAKjUhADir8gAgAAbwARLKj6;w3IBgP___39GAAAAVAAAABgAAACKAAAAG1e9Qk-djUEvZAFCbxA4Q0YAAABUAAAAGAAAAIoAAAC_AQAAp4WNA1XZKQKjg40DF9spAgEA_wIRLKj6";
        // $c8 = "https://testmap.141.ir/route/v1/driving/48.297455,38.2493585;59.6059232,36.2974945?overview=full&alternatives=true&steps=true&hints=_rkTgA-6E4AMAAAAAAAAAHoAAAAAAAAAjsEEQQAAAADBEaJCAAAAAAwAAAAAAAAAegAAAAAAAAC_AQAA8PfgAnqjRwLv9eACj6NHAgUAfxQRLKj6;w3IBgP___39GAAAAVAAAABgAAACKAAAAG1e9Qk-djUEvZAFCbxA4Q0YAAABUAAAAGAAAAIoAAAC_AQAAp4WNA1XZKQKjg40DF9spAgEA_wIRLKj6";
        // $c9 = "https://testmap.141.ir/route/v1/driving/59.6059232,36.2974945;59.794798968359835,35.63056562047708;60.13951487839223,34.401852321294946;60.15858914586716,26.715753176949136;60.6470887,25.293269?overview=full&alternatives=true&steps=true&hints=w3IBgP___39GAAAAVAAAABgAAACKAAAAG1e9Qk-djUEvZAFCbxA4Q0YAAABUAAAAGAAAAIoAAAC_AQAAp4WNA1XZKQKjg40DF9spAgEA_wIRLKj6;SqsBgE2rAYChAAAArAIAALEAAABHAwAABlZ3Q9lzgkR9UYdDDl2gRKEAAACsAgAAsQAAAEcDAAC_AQAAHoOQA8aKHwJvZZAD5q0fAgIAfwMRLKj6;KksKgF7-FoAIAQAAAAAAAFELAAAzGAAAwYjJQwAAAADS_IlFK8oTRggBAAAAAAAAUQsAADMYAAC_AQAA_L-VA3zeDAL7p5UDPO4MAiIA3w0RLKj6;EPQJgL0xDIAbAAAASAAAAEEAAABDAQAAjv2BQnztJ0Oe7xdD92k-RBsAAABIAAAAQQAAAEMBAAC_AQAA2vKVA1ymlwF98pUDaaaXAQEAnwARLKj6;ltBCgJjQQoBGAAAANgAAAAAAAAAAAAAAdEdEQu69E0IAAAAAAAAAAEYAAAA2AAAAAAAAAAAAAAC_AQAADGidA7jxgQGxZp0D1fGBAQAAnwsRLKj6";
        // $c10 = "https://testmap.141.ir/route/v1/driving/45.206595,38.7139034;44.94834333658219,38.49361387989263;46.1658505,33.1239454?overview=full&alternatives=true&steps=true&hints=2JMYgNuTGIAHAAAAYwAAAAgBAAAhAQAA-pqtQEDgiELZDzhDTHpJQwcAAABjAAAACAEAACEBAAC_AQAAocyxAr-5TgJDzLECL7pOAgUAzw4RLKj6;6dgtgP___3_KAAAAPAEAAMoAAACJAAAAZzLuQ87vhUPii-1DM8WhQ8oAAAA8AQAAygAAAIkAAAC_AQAAS92tAnBdSwJ3260Crl1LAgYA3wsRLKj6;OC0JgP___38tAAAANwAAAAYAAABbAAAAwGKkQoWwg0GWjidBsPwjQy0AAAA3AAAABgAAAFsAAAC_AQAASHDAAtNt-QFbb8ACaW75AQEAnw0RLKj6";
        // switch ($request->mehvar_id) {
        //     case 1:
        //         $url = $c1;
        //         break;
        //     case 2:
        //         $url = $c2;
        //         break;
        //     case 3:
        //         $url = $c3;
        //         break;
        //     case 4:
        //         $url = $c4;
        //         break;
        //     case 5:
        //         $url = $c5;
        //         break;
        //     case 6:
        //         $url = $c6;
        //         break;
        //     case 7:
        //         $url = $c7;
        //         break;
        //     case 8:
        //         $url = $c8;
        //         break;
        //     case 9:
        //         $url = $c9;
        //         break;
        //     case 10:
        //         $url = $c10;
        //         break;
        //     default:
        //         # code...
        //         break;
        // }
        // dd();
        /// curl and save response in geo
        // $url = $c1;
        // $result = file_get_contents($url);
        // $result = json_decode($result);
        // $geo = $result->routes[0]->geometry;
        // $points =  \GeometryLibrary\PolyUtil::decode($geo);
        // dd(count($points));
        // foreach($points as $value)
        // 	echo $value['lat'].'  '.$value['lng']."\n";
        // return;
        //// start
        // $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        // $charactersLength = strlen($characters);
        // $randomString = '';
        // for ($i = 0; $i < 20; $i++) {
        //     $randomString .= $characters[rand(0, $charactersLength - 1)];
        // }
        // $id = $randomString;
        // Str::uuid();
        // $id = 1;
        // dd();
        $dat = array();
        $identifier = Str::uuid();
        foreach ($points as $value) {
            array_push($dat, array('lat1'=>$value['lat'], 'lng1'=> $value['lng'], 'identifier' => $identifier));
            // array_push($dat, array('lat1'=>$value['lat'], 'lng1'=> $value['lng'], 'id' => mt_rand(1,9999).time(),'identifier' => $identifier));
            // $id++;
        }
        RoutePath::insert($dat);//// insert

        // dd("hi");
        // $query = "select * from route_paths,road_items_projects  where  (6371 * ACOS( COS( RADIANS(route_paths.lat1) ) * COS( RADIANS(road_items_projects.start_lat) ) * COS( RADIANS(road_items_projects.start_lng) - RADIANS(route_paths.lng1)) + SIN(RADIANS(route_paths.lat1)) * SIN(RADIANS(start_lat)) )    ) < 0.01 and province_id in (9,4,21,23,24,33,35) and created_at between '2021-05-22 00:00:00' and '2021-06-05 23:59:59' group by start_lat,start_lng";



        // $query = "SELECT * FROM road_items_projects rip WHERE EXISTS (SELECT * FROM route_paths rp WHERE ( (6371* ACOS( COS( RADIANS(rp.lat1) ) *  COS( RADIANS(rip.start_lat) ) * COS( RADIANS(rip.start_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(start_lat)))) < 0.02 || (6371 * ACOS( COS( RADIANS(rp.lat1) ) *  COS( RADIANS(rip.end_lat) ) * COS( RADIANS(rip.end_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(end_lat))))<0.02 ) AND rip.created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59')";


        // SELECT * FROM road_items_projects rip WHERE (rip.created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59') AND EXISTS (SELECT * FROM route_paths rp WHERE ( (6371* ACOS( COS( RADIANS(rp.lat1) ) * COS( RADIANS(rip.start_lat) ) * COS( RADIANS(rip.start_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(start_lat)))) < 0.02 || (6371 * ACOS( COS( RADIANS(rp.lat1) ) * COS( RADIANS(rip.end_lat) ) * COS( RADIANS(rip.end_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(end_lat))))<0.02 ) )

        $query = "SELECT *,pdate(created_at) as d FROM route_paths join road_items_projects  WHERE  (  6371   * ACOS( COS( RADIANS(route_paths.lat1) ) * 
		COS( RADIANS(road_items_projects.start_lat) ) * COS( RADIANS(road_items_projects.start_lng) - RADIANS(route_paths.lng1)) +
		 SIN(RADIANS(route_paths.lat1)) * SIN(RADIANS(start_lat)) )    ) < 0.02 
		AND created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59' GROUP BY start_lat,start_lng
		UNION 
		SELECT *,pdate(created_at) as d FROM route_paths join road_items_projects  WHERE  (6371 * ACOS( COS( RADIANS(route_paths.lat1) ) * 
		COS( RADIANS(road_items_projects.end_lat) ) * COS( RADIANS(road_items_projects.end_lng) - RADIANS(route_paths.lng1)) +
		 SIN(RADIANS(route_paths.lat1)) * SIN(RADIANS(end_lat)) )    ) < 0.02 
		AND created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59' GROUP BY end_lat,end_lng";

        // $end_time = microtime(true);
        $result = DB::select($query);
        
        $execution_time = ($end_time - $start_time);
        echo $query;
        echo " It takes ". $execution_time." seconds to execute the script";
        dd($result);
        
        RoutePath::where('identifier', $identifier)->delete();//////  delete  table
        // RoutePath::truncate();//////  delete  table
        ///// end
        $myarr = array();
        $info = InfoItem::all();
        // dd($result);
        foreach ($result as $value) {
            $z = json_decode($value->sub_items_data);
            foreach ($z as $key => $val) {
                foreach ($info as $key1 => $value1) {
                    if ($key == $value1->sub_item_id) {
                        $myarr[] = array(
                            'id' => $key,
                            'id_fa' => $value1->item_str,
                            'sub_id_fa' => $value1->sub_item_str,
                            'unit' => $value1->sub_item_unit,
                            'value' => $val,
                            'province' => $value->province_fa,
                            'city'  => $value->city_fa,
                            'date'  => $value->d
                          );
                    }
                }
                // $myarr['data'][] = array(
                // 	'id' => $key,
                // 	'value' => $val
                // );
                // $val;
                // echo $key.'   '.$val."\n";
            }
        }

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

        ///////////////////////////////////////////////////////////////////END/////////////////////////////////







        dd($myarr);
        $data = array();
        
        foreach ($myarr as $key => $value) {
            foreach ($info as $key1 => $value1) {
                if ($key == $value1->sub_item_id) {
                    $data['results'][] = array(
                        'id' => $key,
                        'id_fa' => $value1->item_str,
                        'sub_id_fa' => $value1->sub_item_str,
                        'unit' => $value1->sub_item_unit,
                        'value' => $value,
                        'province' => $value->province_fa,
                        'city'  => $value->city_fa
                      );
                }
            }
        }
        dd($data);
        // dd($projects);
        // foreach ($projects as $key => $value) {
        // 	echo $value->id."\n";
        // }
        /// bar asase mehvar     province id ha va date time ro where mizarim
        
        $end_time = microtime(true);
        $execution_time = ($end_time - $start_time);
        echo " It takes ". $execution_time." seconds to execute the script";
        return;
        /// distance ba shoaa  1 metre
        /// har kodom bod az araye dovomi ke mishe porozhe ha hazf mishe
        //return response
    }
    
    public function codexworldGetDistanceOpt($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo)
    {
        /**
         * Optimized algorithm from http://www.codexworld.com
         *
         * @param float $latitudeFrom
         * @param float $longitudeFrom
         * @param float $latitudeTo
         * @param float $longitudeTo
         *
         * @return float [km]
         */
        $rad = M_PI / 180;
        $theta = $longitudeFrom - $longitudeTo;
        $dist = sin($latitudeFrom * $rad)
            * sin($latitudeTo * $rad) +  cos($latitudeFrom * $rad)
            * cos($latitudeTo * $rad) * cos($theta * $rad);
        return (acos($dist) / $rad * 60 *  1.853)/1000;
    }







// -- SELECT * FROM road_items_projects rip WHERE (rip.created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59')



// SELECT * FROM (SELECT * FROM road_items_projects rip WHERE (rip.created_at BETWEEN '2021-04-21 00:00:00' AND '2021-06-21 23:59:59')) rip WHERE EXISTS (SELECT * FROM route_paths rp WHERE ( (6371* ACOS( COS( RADIANS(rp.lat1) ) * COS( RADIANS(rip.start_lat) ) * COS( RADIANS(rip.start_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(rip.start_lat)))) < 0.02 || (6371 * ACOS( COS( RADIANS(rp.lat1) ) * COS( RADIANS(rip.end_lat) ) * COS( RADIANS(rip.end_lng) - RADIANS(rp.lng1)) + SIN(RADIANS(rp.lat1)) * SIN(RADIANS(rip.end_lat))))<0.02 ) )


    public function coridorReportById(Request $request){
        $start_time = microtime(true);
        $s_lat = $request->slat;
        $s_lng = $request->slng;
        $d_lat = $request->dlat;
        $d_lng = $request->dlng;
        $date_to = $request->dateto;
        $date_from = $request->datefrom;
        $item = $request->item ?? 0;
        $sub_item = $request->subitem ?? 0;
        ///// start
        $url = "https://testmap.141.ir/route/v1/driving/".$s_lng.",".$s_lat.";".$d_lng.",".$d_lat."?overview=full&alternatives=true&steps=true";
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  

        $result = file_get_contents($url, false, stream_context_create($arrContextOptions));
        // return $result;
        $result = json_decode($result);

        // dd($result->routes[0]->legs[0]->steps);
        $ways = $result->routes[0]->legs[0]->steps;
        // return gettype($ids);
        $ids = array();
        foreach ($ways as $key => $value) {
            if(!in_array($value->name, $ids)){
                $ids[] = $value->name;
            }
        }
        $data = RoadItemsProject::whereIn('start_way_id', $ids)
                                ->orWhereIn('end_way_id', $ids)
                                ->get();
        $end_time = microtime(true);
        $execution_time = ($end_time - $start_time);
        echo " It takes ". $execution_time." seconds to execute the script"."\n";
        return count($data);
    }


    
    public function update_road_items(Request $request){
        $start_time = microtime(true);
        $data = \App\Models\ContractSubItems::whereNull('start_way_id')->get();
        foreach($data as $row){
            $start_id = $this->get_way_id_from_nominatim($row['start_lat'],$row['start_lng']);
            $end_id = $this->get_way_id_from_nominatim($row['end_lat'],$row['end_lng']);
            $q = \App\Models\ContractSubItems::find($row['id']);
            $q->start_way_id = $start_id;
            $q->end_way_id = $end_id;
            $q->save();
        }
        $end_time = microtime(true);
        $execution_time = ($end_time - $start_time);
        echo " It takes ". $execution_time." seconds to execute the script";
        return;
        dd($data);
    }



    function get_way_id_from_nominatim($lat, $lng){
        $url = "https://testmap.141.ir/nominatim/reverse?format=jsonv2&lat=".$lat."&lon=".$lng."&zoom=16&addressdetails=16";
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $result = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $result = json_decode($result);
        if(isset($result->osm_type))
            if($result->osm_type == 'way')
                return $result->osm_id;
        return 0;
    }

    public function axisReportByLatAndLng(Request $request, NominatimService $nominatimService)
    {
        if (! $request->type) {
            return response()->json([
                'status' => 'error',
                'message' => ' لطفا یک گزینه از فیلتر ها را انتخاب نمایید.'
            ], 400);
        }
        $date_to = $request->date_to;
        $date_from = $request->date_from;
        $info_id = $request->daily_activity;
        $roadObservedTypes = $request->road_type;
        $idArrays = $nominatimService->getIDFromNominatim($request->slng, $request->slat, $request->dlng, $request->dlat);
        $typeArrays = $request->type;
        $contractStatusArrays = $request->contract_status ?? [];
        $projectTypeArrays = $request->project_type ?? [];
        $array = [];
        if  ( in_array(1, $typeArrays) ) {
            $roadItemsProject = RoadItemsProject::where(function($query) use($idArrays){
                                                    $query->whereIn("start_way_id", $idArrays)
                                                    ->orWhereIn("end_way_id", $idArrays);
                                                })
                                                ->WhereIn("info_id", $info_id)
                                                ->whereBetween("created_at", [$date_from . " 00:00:00", $date_to . " 23:59:59"])                          
                                                ->select("start_lat", "start_lng", "id")
                                                ->get();

        }
        
        if ( in_array(2, $typeArrays) ) {
            $roadPatrolProject = RoadPatrol::where(function($query) use($idArrays){
                                                        $query->whereIn("start_way_id", $idArrays)
                                                        ->orWhereIn("end_way_id", $idArrays);
                                                    })
                                                    ->whereBetween('created_at', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                           
                                                    ->whereNotNull('start_lat')
                                                    ->select('start_lat', 'start_lon', 'id')
                                                    ->get();
        }
        
        if ( in_array(3, $typeArrays) ) {
            $contractSubItems = \App\Models\ContractSubItems::where(function($query) use($idArrays){
                                                                $query->whereIn("start_way_id", $idArrays)
                                                                ->orWhereIn("end_way_id", $idArrays);
                                                            })
                                                            ->whereBetween('contract_date_from_parent_contract', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                            
                                                            ->when($contractStatusArrays , function ($query) use ($contractStatusArrays) {
                                                                $query->whereIn('last_status_id', $contractStatusArrays);
                                                            })
                                                            ->when($projectTypeArrays , function ($query) use ($projectTypeArrays) {
                                                                $query->whereIn('project_type_id', $projectTypeArrays);
                                                            })
                                                            ->select('start_lat', 'start_lng', 'id')
                                                            ->get();
        }
        
        if ( in_array(4, $typeArrays) ) {
            $roadObserved = \App\Models\RoadObserved::where(function($query) use($idArrays){
                                                        $query->whereIn("handling_way_id", $idArrays)
                                                        ->orWhereIn("observed_way_id", $idArrays);
                                                    })
                                                    ->whereIn('fk_FeatureType', $roadObservedTypes)
                                                    ->select('rms_start_latlng', 'id','lat', 'lng')
                                                    ->where('rms_status', '<>', 0)
                                                    ->whereBetween('created_at', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                           
                                                    ->get();
            
            $roadObservedArray = [];
            foreach ($roadObserved as $value) {
                $roadObservedArray[] = [
                    'id' => $value->id,
                    'start_lat' => $value->rms_start_latlng[0] ?? $value->lat,
                    'start_lng' => $value->rms_start_latlng[1] ?? $value->lng,
                ];
            }
        }

        $array['roadItemsProject'] = $roadItemsProject ?? null;
        $array['roadPatrolProject'] = $roadPatrolProject ?? null;
        $array['contractSubItems'] = $contractSubItems ?? null;
        $array['roadObserved'] = $roadObservedArray ?? null;

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

    public function getAxisReportDataFromID(Request $request)
    {
        switch ($request->type) {
            case "1":
                $data = RoadItemsProject::with('files')->find($request->id);
                break;
            case "2":
                $data = RoadPatrol::find($request->id);
                break;
            case "3":
                $collection = \App\Models\ContractSubItems::whereId($request->id)->get();
                foreach ($collection as $item) {
                    $data[] = [
                        'province_fa' => $item->province_fa,
                        'city_fa' => $item->city_fa,
                        'project_type_fa' => $item->project_type_fa,
                        'project_type_id' => $item->project_type_id,
                        'progress_project' => $item->progress_project,
                        'project_title' => $item->project_title,
                        'axis_type_fa' => $item->axis_type_fa,
                        'axis_name_fa' => $item->axis_name_fa,
                        'last_status_fa' => $item->last_status_fa,
                        'created_at_fa' => $item->created_at_fa,
                        'updated_at_fa' => $item->updated_at_fa,
                        'operator_name' => $item->operator_name,
                        'start_lat' => $item->start_lat,
                        'end_lat' => $item->end_lat,
                        'start_lng' => $item->start_lng,
                        'end_lng' => $item->end_lng,
                        'image_path1' => $item->image_path1,
                        'image_path2' => $item->image_path2,
                        'operation' => [
                            [
                                'hasOperation' => $item->operation_type_id1 != 0 ? 1 : 0,
                                'operation_type_id1' => $item->operation_type_id1,
                                'operation_type_fa1' => $item->operation_type_fa1,
                                'operation_type_unit1' => $item->operation_type_unit1 == "" ? "-" : $item->operation_type_unit1,
                                'operation_type_amount1' => $item->operation_type_amount1 ?? "-",
                                'operation_type_progress1' => $item->operation_type_progress1,
                                'operation_type_tonaj1' => $item->operation_type_tonaj1 ?? "-",
                            ],
                            [
                                'hasOperation' => $item->operation_type_id2 != 0 ? 1 : 0,
                                'operation_type_id2' => $item->operation_type_id2,
                                'operation_type_fa2' => $item->operation_type_fa2,
                                'operation_type_unit2' => $item->operation_type_unit2 == "" ? "-" : $item->operation_type_unit2,
                                'operation_type_amount2' => $item->operation_type_amount2 ?? "-",
                                'operation_type_progress2' => $item->operation_type_progress2,
                                'operation_type_tonaj2' => $item->operation_type_tonaj2 ?? "-",
                            ],
                            [
                                'hasOperation' => $item->operation_type_id3 != 0 ? 1 : 0,
                                'operation_type_id3' => $item->operation_type_id3,
                                'operation_type_fa3' => $item->operation_type_fa3,
                                'operation_type_unit3' => $item->operation_type_unit3 == "" ? "-" : $item->operation_type_unit3,
                                'operation_type_amount3' => $item->operation_type_amount3 ?? "-",
                                'operation_type_progress3' => $item->operation_type_progress3,
                                'operation_type_tonaj3' => $item->operation_type_tonaj3 ?? "-",
                            ],
                            [
                                'hasOperation' => $item->operation_type_id4 != 0 ? 1 : 0,
                                'operation_type_id4' => $item->operation_type_id4,
                                'operation_type_fa4' => $item->operation_type_fa4,
                                'operation_type_unit4' => $item->operation_type_unit4 == "" ? "-" : $item->operation_type_unit4,
                                'operation_type_amount4' => $item->operation_type_amount4 ?? "-",
                                'operation_type_progress4' => $item->operation_type_progress4,
                                'operation_type_tonaj4' => $item->operation_type_tonaj4 ?? "-"
                            ]
                        ]
                    ];
                }
                break;
            case "4":
                $data = \App\Models\RoadObserved::where('id', $request->id)->with('files')->first();
                break;
            default:
                break;
        }
        
        return response()->json([
            'message' => 'success',
            'data' => $data
        ], 200);
    }

    function getIDFromNominatim($s_lng, $s_lat, $d_lng, $d_lat)
    {
        $url = "https://testmap.141.ir/route/v1/driving/".$s_lng.",".$s_lat.";".$d_lng.",".$d_lat."?overview=full&alternatives=true&steps=true";
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );  
        $result = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $result = json_decode($result);
        if(count($result->routes) > 1 && $result->routes[1]->distance < $result->routes[0]->distance){ 
            // if(){
                $ways = $result->routes[1]->legs[0]->steps;
            // }
        }
        else
            $ways = $result->routes[0]->legs[0]->steps;
        $ids = array();
        foreach ($ways as $key => $value) {
            if(!in_array($value->name, $ids)){
                $ids[] = $value->name;
            }
        }

        return $ids;
    }


    public function axisReportExcelRedirector(Request $request, NominatimService $nominatimService)
    {
        if (! $request->type) {
            return response()->json([
                'status' => 'error',
                'message' => ' لطفا یک گزینه از فیلتر ها را انتخاب نمایید.'
            ], 400);
        }
        $date_to = $request->date_to;
        $date_from = $request->date_from;
        $info_id = $request->daily_activity;
        $roadObservedTypes = $request->road_type;
        $idArrays = $nominatimService->getIDFromNominatim($request->slng, $request->slat, $request->dlng, $request->dlat);
        $typeArrays = $request->type;
        $contractStatusArrays = $request->contract_status ?? [];
        $projectTypeArrays = $request->project_type ?? [];
        $array = [];
        // dd( $request->date_to);
        if  ( in_array(1, $typeArrays) ) {
            $roadItemsProject = RoadItemsProject::where(function($query) use($idArrays){
                                                    $query->whereIn("start_way_id", $idArrays)
                                                    ->orWhereIn("end_way_id", $idArrays);
                                                })
                                                ->WhereIn("info_id", $info_id)
                                                // ->when($date_to , function ($query) use ($date_to, $date_from) {
                                                ->whereBetween("created_at", [$date_from . " 00:00:00", $date_to . " 23:59:59"])                          
                                                // })
                                                // ->whereNotNull("start_lat")
                                                ->select("start_lat", "start_lng", "id")
                                                // ->toSql();
                                                // echo $roadItemsProject;
                                                // dd($roadItemsProject);                                   
                                                ->get();

        }
        
        if ( in_array(2, $typeArrays) ) {
            $roadPatrolProject = RoadPatrol::whereIn('start_way_id', $idArrays)
                                                            ->orWhereIn('end_way_id', $idArrays)
                                                            // ->when($date_to , function ($query) use ($date_to, $date_from) {
                                                            ->whereBetween('created_at', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                           
                                                            // })
                                                            ->whereNotNull('start_lat')
                                                            ->select('start_lat', 'start_lon', 'id')
                                                            ->get();
        }
        
        if ( in_array(3, $typeArrays) ) {
            $contractSubItems = \App\Models\ContractSubItems::whereIn('start_way_id', $idArrays)
                                                            ->orWhereIn('end_way_id', $idArrays)
                                                            // ->when($date_to , function ($query) use ($date_to, $date_from) {
                                                            ->whereBetween('contract_date_from_parent_contract', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                            
                                                            // })
                                                            ->with('Contracts')
                                                            // ->whereNotNull('start_lat')
                                                            ->when($contractStatusArrays , function ($query) use ($contractStatusArrays) {
                                                                // $query->whereHas('Contracts', function($query) use ($contractStatusArrays) {
                                                                    $query->whereIn('last_status_id', $contractStatusArrays);
                                                                // });
                                                            })
                                                            ->when($projectTypeArrays , function ($query) use ($projectTypeArrays) {
                                                                $query->WhereIn('project_type_id', $projectTypeArrays);
                                                            })
                                                            ->select('start_lat', 'start_lng', 'id')
                                                            ->get();
        }
        
        if ( in_array(4, $typeArrays) ) {
            $roadObserved = \App\Models\RoadObserved::where(function($query) use($idArrays){
                                                        $query->whereIn("handling_way_id", $idArrays)
                                                        ->orWhereIn("observed_way_id", $idArrays);
                                                    })
                                                    ->whereIn('fk_FeatureType', $roadObservedTypes)
                                                    ->select('rms_start_latlng', 'id')
                                                    // ->when($date_to , function ($query) use ($date_to, $date_from) {
                                                    ->whereBetween('created_at', [$date_from . ' 00:00:00', $date_to . ' 23:59:59'])                           
                                                    // })
                                                    ->get();
            
            $roadObservedArray = [];
            foreach ($roadObserved as $value) {
                $roadObservedArray[] = [
                    'id' => $value->id,
                    'start_lat' => $value->rms_start_latlng[0] ?? null,
                    'start_lng' => $value->rms_start_latlng[1] ?? null,
                ];
            }
        }

        $array['roadItemsProject'] = $roadItemsProject ?? null;
        $array['roadPatrolProject'] = $roadPatrolProject ?? null;
        $array['contractSubItems'] = $contractSubItems ?? null;
        $array['roadObserved'] = $roadObservedArray ?? null;

        if ($array['roadItemsProject'] != null) {
            foreach ($array['roadItemsProject'] as $item) {
                $activities[] = $item->id;
            }
        }
        if ($array['roadPatrolProject'] != null) {
            foreach ($array['roadPatrolProject'] as $item) {
                $patrols[] = $item->id;
            }
        }
        if ($array['contractSubItems'] != null) {
            foreach ($array['contractSubItems'] as $item) {
                $projects[] = $item->id;
            }
        }
        if ($array['roadObserved'] != null) {
            foreach ($array['roadObserved'] as $item) {
                $observeds[] = $item['id'];
            }
        }

        $name = 'گزارش گیری محوری ' . verta()->now()->format('Y-m-d H-i') . '.xlsx';
        return Excel::download(new AxisReportsSheets($patrols ?? null, $activities ?? null, $projects ?? null, $observeds ?? null, $date_from, $date_to), $name);
        // dd($roadItemsProject);
        // if (isset($activities) || isset($patrols) || isset($observeds) || isset($projects)) {
        // } else {
        //     # code...
        // }
        

    }
}