<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use App\Models\RoadPatrolProject;
use Illuminate\Support\Facades\Auth;

class RoadPatrolProjectController extends Controller
{

    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 store(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1032);
        }
        $roadProject = new RoadPatrolProject();
        $request['source'] = explode(',', $request['source']);
        $request['dest'] = explode(',', $request['dest']);

        $roadProject->start_lat = $request['source'][0];
        $roadProject->start_lng = $request['source'][1];
        $roadProject->end_lat = $request['dest'][0];
        $roadProject->end_lng = $request['dest'][1];
        $roadProject->project_distance = $request['distance'];////// i added below line
        $roadProject->province_fa = Auth::user()->province_fa;
        $roadProject->province_id = Auth::user()->province_id;
        $roadProject->city_id = Auth::user()->city_id;
        $roadProject->city_fa = Auth::user()->city_fa ?? Auth::user()->name;
        $roadProject->start_way_id = self::get_way_id_from_nominatim($request['source'][0], $request['source'][1]);
        $roadProject->end_way_id = self::get_way_id_from_nominatim($request['dest'][0], $request['dest'][1]);

        //// end of my edit

        // begin V2 refactor
        $roadProject->status = 0;
        $roadProject->status_fa = 'در حال بررسی';
        // end V2 refactor

        $roadPatrol = $request->user()->roadPatrolProjects()->save($roadProject);

        $item_index = 0;
        $item_array = [];

        while (true) {
            if ($request['item_' . $item_index]) {
                $request['latlng_' . $item_index] = explode(',', $request['latlng_' . $item_index]);
                $item_array[$item_index]['project_lat'] = $request['latlng_' . $item_index][0] ?? null;
                $item_array[$item_index]['project_lng'] = $request['latlng_' . $item_index][1] ?? null;
                $item_array[$item_index]['item'] = $request['item_' . $item_index] ?? null;
                $item_array[$item_index]['sub_items'] = explode(',', $request['subitems_' . $item_index]);
                $item_array[$item_index]['sub_items_data'] = json_decode($request['data_' . $item_index]) ?? null;
                
                $roadSubProject = $roadPatrol->roadPatrolSubProjects()->create($item_array[$item_index]);
                
                $file_index = 0;
                $files_path = [];
                while (true) {
                    if ($request['file_' . $item_index . '_' . $file_index]) {
                        $files_path[$file_index]['path'] = $request->file('file_' . $item_index . '_' . $file_index)
                            ->store('public/road_patrol_projects');
                        $file_index++;
                    } else {
                        break;
                    }
                }

                if ($file_index > 0) {
                    $roadSubProject->files()->createMany($files_path);
                }

                $item_index++;
            } else {
                break;
            }
        }

        return response()->json([
            'status' => 'succeed',
            'message' => ''
        ], 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function statics(){
        $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]); 

        $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 = RoadPatrolProject::whereBetween('created_at', [$date_from." 00:00:00",
                                $date_to_day." 23:59:59"])
                                ->count();
        $weak = RoadPatrolProject::whereBetween('created_at', [$start_week[0]."-".$start_week[1]."-".$start_week[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $month = RoadPatrolProject::whereBetween('created_at', [$start_month[0]."-".$start_month[1]."-".$start_month[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $year = RoadPatrolProject::whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        return response()->json([
            'today' => $day,
            'week'  => $weak,
            'month' => $month,
            'year'  => $year
        ]);
    }
}