<?php

namespace App\Http\Controllers;

use App\Models\InfoItem;

use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use App\Models\RoadItemsProject;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\RoadPatrolProject;
use App\Models\EdarateOstani;
use App\Models\EdarateShahri;

class RoadItemsProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => Auth::user()->roadItemsProjects()->with('user')->get()
        ], 200);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function indexPublic()
    {
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => RoadItemsProject::where('id', '<', 5)->with('user')->get()
        ], 200);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('rmto-preview.pages.road-items');
    }



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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'after_image' => 'required',
            'before_image' => 'required',
        ]);

        $roadProject = new RoadItemsProject();

        $request['source_coordinates'] = explode(',', $request['source_coordinates']);
        $request['dest_coordinates'] = explode(',', $request['dest_coordinates']);

        $roadProject->start_lat = $request['source_coordinates'][0] ?? null;
        $roadProject->start_lng = $request['source_coordinates'][1] ?? null;
        $roadProject->end_lat = $request['dest_coordinates'][0] ?? null;
        $roadProject->end_lng = $request['dest_coordinates'][1] ?? null;
        $roadProject->project_distance = $request['total_distance'] ?? null;
        $roadProject->item = $request['item'] ?? null;
        $roadProject->start_way_id = self::get_way_id_from_nominatim($roadProject->start_lat, $roadProject->start_lng);
        $roadProject->end_way_id = self::get_way_id_from_nominatim($roadProject->end_lat, $roadProject->end_lng);
        #nmto_must_deleted begin
        $roadProject->sub_items = explode('-', substr($request['sub_items'], 0, -1));
        $roadProject->sub_items_data = json_decode($request['sub_items_data']) ?? null;
        #nmto_must_deleted end

        #new begin
        $request['sub_items'] = explode('-', substr($request['sub_items'], 0, -1));
        $temp_item = InfoItem::where('item', $request['item'])->where('sub_item', $request['sub_items'])->first();
        foreach ($roadProject->sub_items_data as $key => $value) {
            $roadProject->sub_item_data = $value;
        }
        $roadProject->item_fa = $temp_item->item_str;
        $roadProject->sub_item = $temp_item->sub_item;
        $roadProject->sub_item_fa = $temp_item->sub_item_str;
        #new end

        #new_2 begin
        $roadProject->unit_fa = $temp_item->sub_item_unit;
        $roadProject->created_at_fa = verta(\Carbon\Carbon::now())->format('Y-m-d H:i:s');
        $roadProject->user_name = Auth::user()->name;
        $roadProject->info_id = $temp_item->id;
        #new_2 end

        $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;

        // begin V2 refactor
        if (Auth::user()->edarate_shahri_id) {
            $roadProject->edarat_id = Auth::user()->edarate_shahri_id;
            $roadProject->edarat_type = EdarateShahri::class;
            $roadProject->edarat_name = Auth::user()->edarate_shahri_name;
        } elseif (Auth::user()->edarate_ostani_id) {
            $roadProject->edarat_id = Auth::user()->edarate_ostani_id;
            $roadProject->edarat_type = EdarateOstani::class;
            $roadProject->edarat_name = Auth::user()->edarate_ostani_name;
        }
        // else{
        //     return response()->json([
        //         'message' => 'اداره شهری یا استانی برای شما در سامانه ثبت نشده است!'
        //     ], 400);
        // }

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

        $roadItems = $request->user()->roadItemsProjects()->save($roadProject);

        if ($request->has('after_image')) {
            $after = $request->file('after_image')->store('road_items_projects_new/after', 'public');
            $roadItems->files()->create(['path' => $after]);
            $urlAfter = "/var/www/rms/public/storage/{$after}";
//            \App\Helpers\Compress::resize($urlAfter);
        }
        if ($request->has('before_image')) {
            $before = $request->file('before_image')->store('/road_items_projects_new/before', 'public');
            $roadItems->files()->create(['path' => $before]);
            $urlBefore = "/var/www/rms/public/storage/{$before}";
//            \App\Helpers\Compress::resize($urlBefore);
        }

        if (auth()->user()) {
            auth()->user()->addActivityComplete(1031);
        }

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


    public function show($id)
    {
        $project = RoadItemsProject::where('id', $id)->with('files')->first();

        if ($project && (
            $project->user_id == Auth::user()->id
            || Auth::user()->id <= 35
            || Auth::user()->id == 470
            || Auth::user()->id == 469
            || Auth::user()->province_id == $project->user->province_id
        )) {
            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $project
            ], 200);
        } else {
            return response()->json([
                'status' => 'succeed',
                'message' => ''
            ], 200);
        }
    }

    public function showPublic($id)
    {
        // $sql = DB::select(DB::raw("SELECT provinces.`name_fa` AS province_fa,cities.`name_fa` AS city_fa,
        //         road_items_projects.`sub_items_data` AS sub,road_items_projects.`project_distance`,
        //         road_items_projects.item,road_items_projects.created_at
        //         FROM road_items_projects JOIN users ON users.`id` = road_items_projects.`user_id`
        //         INNER JOIN provinces ON provinces.id = users.`province_id`
        //         INNER JOIN cities ON cities.`id` = users.`city_id`
        //         INNER JOIN info_items ON info_items.`item` = road_items_projects.`item`
        //         WHERE road_items_projects.id = ".$id." GROUP BY road_items_projects.item"));

        // $keys = DB::select(DB::raw("SELECT JSON_KEYS(road_items_projects.`sub_items_data`) as k
        // FROM road_items_projects
        // WHERE road_items_projects.id = ".$id));
        // $items = InfoItem::whereIn('sub_item_id', json_decode($keys[0]->k))->get();
        // $sql[0]->sub = json_decode($sql[0]->sub);
        $road_item = RoadItemsProject::find($id);

        return response()->json([
            'status' => 'succeed',
            'picture' => $road_item->files,
            'message' => '',
            'items' => $road_item->toArray(),
            // 'data' => $sql
        ], 200);
    }

    public function edit($id)
    {
        $project = RoadItemsProject::find($id);

        if ($project && (
            $project->user_id == Auth::user()->id
            || Auth::user()->id <= 35
            || Auth::user()->id == 470
        )) {
            return redirect('road-items/create?id=' . $id . '&type=1');
        } else {
            return redirect('users/projects');
        }
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'source_coordinates' => 'required|string',
            'dest_coordinates' => 'required|string',
            'total_distance' => 'required|string',
            'item' => 'required|integer',
            'sub_items' => 'string',
            'sub_items_data' => 'string',
            'after_image' => 'required',
            'before_image' => 'required',
        ]);

        $roadProject = RoadItemsProject::find($id);

        $request['source_coordinates'] = explode(',', $request['source_coordinates']);
        $request['dest_coordinates'] = explode(',', $request['dest_coordinates']);

        $roadProject->start_lat = $request['source_coordinates'][0] ?? $roadProject->start_lat;
        $roadProject->start_lng = $request['source_coordinates'][1] ?? $roadProject->start_lng;
        $roadProject->end_lat = $request['dest_coordinates'][0] ?? $roadProject->end_lat;
        $roadProject->end_lng = $request['dest_coordinates'][1] ?? $roadProject->end_lng;
        $roadProject->project_distance = $request['total_distance'] ?? $roadProject->project_distance;
        $roadProject->item = $request['item'] ?? $roadProject->item;


        #nmto_must_deleted begin
        if ($request['sub_items']) {
            $roadProject->sub_items = explode('-', substr($request['sub_items'], 0, -1));
        }
        $roadProject->sub_items_data = json_decode($request['sub_items_data']) ?? $roadProject->sub_items_data;
        #nmto_must_deleted end

        #new begin
        $request['sub_items'] = explode('-', substr($request['sub_items'], 0, -1));
        $temp_item = InfoItem::where('item', $request['item'])->where('sub_item', $request['sub_items'])->first();
        foreach ($roadProject->sub_items_data as $key => $value) {
            $roadProject->sub_item_data = $value;
        }
        $roadProject->item_fa = $temp_item->item_str;
        $roadProject->sub_item = $temp_item->sub_item;
        $roadProject->sub_item_fa = $temp_item->sub_item_str;
        $roadProject->info_id = $temp_item->id;
        #new end

        #new_2 begin
        $roadProject->unit_fa = $temp_item->sub_item_unit;
        #new_2 end

        $roadProject->save();

        if ($request->has('after_image')) {
            $after = $request->file('after_image')->store('road_items_projects_new/after', 'public');
            // $roadProject->files()->delete();
            $roadProject->files()->create(['path' => $after]);
        }
        if ($request->has('before_image')) {
            $before = $request->file('before_image')->store('road_items_projects_new/before', 'public');
            $roadProject->files()->create(['path' => $before]);
        }

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

    /**
     * View road items project page.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function viewProject($id)
    {
        $project = RoadItemsProject::find($id);

        if ($project && (
            $project->user_id == Auth::user()->id
            || Auth::user()->id <= 35
            || Auth::user()->id == 470
            || Auth::user()->province_id == $project->user->province_id
        )) {
            return redirect('projects/riview?id=' . $id);
        } else {
            return redirect('users/projects');
        }
    }

    /**
     * Project get view page.
     *
     * @return \Illuminate\Http\Response
     */
    public function viewProjectPage()
    {
        return view('rmto-preview.pages.road-items-view');
    }

    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"));
        $patroll_day = RoadPatrolProject::whereBetween('created_at', [$date_from." 00:00:00",
                                $date_to_day." 23:59:59"])
                                ->count();
        $patroll_weak = RoadPatrolProject::whereBetween('created_at', [$start_week[0]."-".$start_week[1]."-".$start_week[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $patroll_month = RoadPatrolProject::whereBetween('created_at', [$start_month[0]."-".$start_month[1]."-".$start_month[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();
        $patroll_year = RoadPatrolProject::whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();

        $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 = RoadItemsProject::whereBetween('created_at', [\Carbon\Carbon::now()->format('Y-m-d') ." 00:00:00",
                                                            \Carbon\Carbon::now()->format('Y-m-d') ." 23:59:59"])
                                ->count();

        $weak = RoadItemsProject::whereBetween('created_at', [$start_week[0]."-".$start_week[1]."-".$start_week[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();

        $month = RoadItemsProject::whereBetween('created_at', [$start_month[0]."-".$start_month[1]."-".$start_month[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();

        $year = RoadItemsProject::whereBetween('created_at', [$start_year[0]."-".$start_year[1]."-".$start_year[2]." 00:00:00",
                                $date_from." 23:59:59"])
                                ->count();

        return response()->json([
            'patrol_today' => $patroll_day,
            'patrol_week'  => $patroll_weak,
            'patrol_month' => $patroll_month,
            'patrol_year'  => $patroll_year,
            'today' => $day,
            'week'  => $weak,
            'month' => $month,
            'year'  => $year
        ]);
    }
    //////  function show items on map
    // sharareh begin 
    // public function show_item(Request $request)
    // {
    //     $province = $request->province_id;
    //     $city = $request->city_id;
    //     $sub = $request->sub_id;

    //     if ($request->date_from && $request->date_to) {
    //         $date_from = $request->date_from.' 00:00:00';
    //         $date_to = $request->date_to.' 23:59:59';
    //     } else {
    //         $date_from = Date('Y-m-d');
    //         $date_to = new \DateTime('tomorrow');
    //         $date_to = $date_to->format('Y-m-d');
    //     }
    //     $datass = DB::table('road_items_projects')
    //                 ->where('is_new', 1)
    //                 ->when($province, function ($query, $province) {
    //                     return $query->where('road_items_projects.province_id', $province);
    //                 })
    //                 ->when($city, function ($query, $city) {
    //                     return $query->where('road_items_projects.city_id', $city);
    //                 })
    //                 ->when($sub, function ($query, $sub) {
    //                     return $query->where('sub_items', 'like', '%"'.$sub.'"%');
    //                 })
    //                 ->when($request->item, function ($query) use ($request) {
    //                     if ($request->item > 0) {
    //                         return $query->where('item', $request->item);
    //                     }
    //                     return $query;
    //                 })
    //                 ->when(!is_null($request->status), function ($query) use ($request) {
    //                     return $query->where('status', $request->status);
    //                 })
    //                 ->leftJoin('users', 'users.id', '=', 'road_items_projects.user_id')
    //                 ->whereBetween('road_items_projects.activity_date', [
    //                     $date_from,
    //                     $date_to,
    //                 ])
    //                 ->select('road_items_projects.id as i', 'start_lat as l', 'start_lng as g', 'status')
    //                 ->get();
    //     // dd($datass);

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


    public function table3InRoadItemProject(Request $request)
    {
        $request->validate([
            'start-date' => 'date_format:Y-m-d',
            'end-date' => 'date_format:Y-m-d'
        ]);
        $user = Auth::user();
        $provinceID = $user->province_id;

        if ($request->input('start-date') && $request->input('end-date')) {
            $startDate = date($request->input('start-date') . ' 00:00:00');
            $endtDate = date($request->input('end-date') . ' 23:59:59');
        } else {
            $startDate = date('Y-m-d 00:00:00');
            $endtDate = date('Y-m-d H:i:s');
        }



        if ($user->hasPermissionTo('report-road-item-province')) {
            $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('province_id', $provinceID);
                })
                ->get();
            $roadPatrolProjects = \App\Models\RoadPatrolProject::whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('province_id', $provinceID);
                })
                ->get();
            $fastReactionProjects = \App\Models\RoadObserved::where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                ->when($provinceID, function ($query, $provinceID) {
                    return $query->where('rms_province_id', $provinceID);
                })
                ->get();

            if ($request->develop) {
                dd(1);
            }
        } elseif ($user->hasPermissionTo('report-road-item')) {
            $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
                // ->where('province_id', Auth::user()->province_id)
                ->get();
            $roadPatrolProjects = \App\Models\RoadPatrolProject::whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
            // ->where('province_id', Auth::user()->province_id)
                ->get();
            $fastReactionProjects = \App\Models\RoadObserved::where('road_observeds.rms_status', 1)
                ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
                // ->where('rms_province_id', Auth::user()->province_id)
                ->get();

            if ($request->develop) {
                dd(2);
            }
        } else {
            $roadItemsProjects  = array();
            $roadPatrolProjects =array();
            $fastReactionProjects =array();

            if ($request->develop) {
                dd(3);
            }
        }


        // if (Auth::user()->username == 'witel' || Auth::user()->username == 'drdanesh') {

        // } else {
        //     $roadItemsProjects = \App\Models\RoadItemsProject::whereBetween('road_items_projects.created_at', [$startDate, $endtDate])
        //         ->where('province_id', Auth::user()->province_id)
        //         ->get();
        //     $roadPatrolProjects = \App\Models\RoadPatrolProject::whereBetween('road_patrol_projects.created_at', [$startDate, $endtDate])
        //     ->where('province_id', Auth::user()->province_id)
        //         ->get();
        //     $fastReactionProjects = \App\Models\RoadObserved::where('road_observeds.rms_status', 1)
        //         ->whereBetween('road_observeds.created_at', [$startDate, $endtDate])
        //         ->where('rms_province_id', Auth::user()->province_id)
        //         ->get();
        // }
        $projectCollection = new \Illuminate\Support\Collection();
        $projectCollectionTemp = new \Illuminate\Support\Collection();

        foreach ($roadItemsProjects as $roadItemsProject) {
            $canDelete = 1;

            $project = [
                'id' => $roadItemsProject->id,
                'user' => $roadItemsProject->user->name,
                'province' => $roadItemsProject->user->province_fa,
                'type' => 'فعالیت روزانه و جاری راهداری',
                'item' => $roadItemsProject->item,
                'sub_items' => $roadItemsProject->sub_item,
                'sub_items_data' => $roadItemsProject->sub_item_data,
                'unit_fa' => $roadItemsProject->unit_fa ?? "-",
                'created_at_jalali' => verta($roadItemsProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadItemsProject->created_at->toDateTimeString(),
                'can_delete' => $canDelete
            ];

            $projectCollection->add($project);
        }

        foreach ($roadPatrolProjects as $roadPatrolProject) {
            if ($roadPatrolProject->user->username == 'witel' || $roadPatrolProject->user->username == 'drdanesh') {
                continue;
            }

            $subProjects = $roadPatrolProject->roadPatrolSubProjects()
                ->get();

            $subItems = [];

            foreach ($subProjects as $key => $subProject) {
                $subItems[$key] = [
                    'item' => $subProject->item,
                    'sub_items' => $subProject->sub_items,
                    'sub_items_data' => $subProject->sub_items_data
                ];
            }

            $canDelete = 1;

            $project = [
                'id' => $roadPatrolProject->id,
                'user' => $roadPatrolProject->user->name,
                'province' => $roadPatrolProject->user->province_fa,
                'type' => 'گشت راهداری و ترابری',
                'created_at_jalali' => verta($roadPatrolProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $roadPatrolProject->created_at->toDateTimeString(),
                'sub_projects' => $subItems,
                'can_delete' => $canDelete
            ];
            $projectCollection->add($project);
        }

        foreach ($fastReactionProjects as $fastReactionProject) {
            $project = [
                'id' => $fastReactionProject->id,
                'user' => 'شهرستان ' . $fastReactionProject->TownName,
                'province' => $fastReactionProject->ProvinceName,
                'type' => 'واکنش سریع',
                'created_at_jalali' => verta($fastReactionProject->created_at)->format('Y/m/d - H:i'),
                'created_at' => $fastReactionProject->created_at->toDateTimeString(),
                'can_delete' => 0
            ];
            $projectCollection->add($project);
        }

        $projectCollection = $projectCollection->sortByDesc('created_at');

        foreach ($projectCollection as $project) {
            $projectCollectionTemp->add($project);
        }

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