<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RahdariPoint;
use Hekmatinasser\Verta\Facades\Verta;
use App\Models\Province;
use App\Models\City;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

class RahdariPointController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (auth()->user()) {
            auth()->user()->addActivityComplete(1019);
        }

        $province = $request->province ?? null;
        $status = $request->status ?? null;
        $type = $request->type ?? null;


        /// [START] tollhouse_show_data_index
        $points = null;
        if (Auth::user()->can('show-tollhouse')) {
            $points = RahdariPoint::with('files')
            ->when($province, function($query, $province) {
                return $query->where('province_id', $province);
            })
            ->when($status, function($query, $status) {
                return $query->where('status', $status);
            })
            ->when($type, function($query, $type) {
                return $query->where('type', $type);
            })
            ->get();
        } elseif (Auth::user()->can('show-tollhouse-province')) {
            $points = RahdariPoint::with('files')
            ->where('province_id', Auth::user()->province_id)
            ->when($province, function($query, $province) {
                return $query->where('province_id', $province);
            })
            ->when($status, function($query, $status) {
                return $query->where('status', $status);
            })
            ->when($type, function($query, $type) {
                return $query->where('type', $type);
            })
            ->get();
        } else {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] tollhouse_show_data_index


        $rahdariArray = [];
        foreach ($points as $key => $value) {
            $rahdariArray[$key] = $value;
            /// [START] proposal_edit_data_index
            if (Auth::user()->can('edit-tollhouse')) {
                $rahdariArray[$key]['canEdit'] = 1;
            } elseif (Auth::user()->can('edit-tollhouse-province')) {
                if ($value->province_id == Auth::user()->province_id) {
                    $rahdariArray[$key]['canEdit'] = 1;
                } else {
                    $rahdariArray[$key]['canEdit'] = 0;
                }
            } else {
                $rahdariArray[$key]['canEdit'] = 0;
            }
            /// [END] proposal_edit_data_index


            /// [START] proposal_delete_data_index
            if (Auth::user()->can('delete-tollhouse')) {
                $rahdariArray[$key]['canDelete'] = 1;
            } elseif (Auth::user()->can('delete-tollhouse-province')) {
                if ($value->province_id == Auth::user()->province_id) {
                    $rahdariArray[$key]['canDelete'] = 1;
                } else {
                    $rahdariArray[$key]['canDelete'] = 0;
                }
            } else {
                $rahdariArray[$key]['canDelete'] = 0;
            }
            /// [END] proposal_delete_data_index
        }


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


    public function MapFilterForRahdarkhaneh(Request $request)
    {
        // dd($request->province);
        $province = $request->province_id ?? null;
        $status = $request->status ?? null;
        $type = $request->type ?? null;

        $data = RahdariPoint::with('files')
        ->when($province, function ($query) use ($province) {
            return $query->whereIn('province_id', $province);
        })
        ->when($status, function($query, $status) {
            return $query->whereIn('status', $status);
        })
        ->when($type, function($query, $type) {
            return $query->whereIn('type', $type);
        })
        ->get();
        
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $data,
        ], 200);
    }

    public function index_view()
    {
        /// [START] tollhouse_show_data_view
        if (Auth::user()->can('show-tollhouse') || Auth::user()->can('show-tollhouse-province')) {
            return view('rmto-preview.pages.rahdari-rmto');
        }
        /// [END] tollhouse_show_data_view

        abort(403);
    }

    public function indextest()
    {
        $points = RahdariPoint::with('files')->get();

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

    public function indexFor141()
    {
        $points = RahdariPoint::all();

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

    public function store(Request $request)
    {
        /// [START] tollhouse_add_data_store
        if (!(Auth::user()->can('add-tollhouse') || (Auth::user()->can('add-tollhouse-province') && $request->province_id == Auth::user()->province_id))) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] tollhouse_add_data_store

        foreach (Province::where('id', $request->province_id)->get() as $province) {
            $province_name = $province->name_fa;
        }

        foreach (City::where('id', $request->city_id)->get() as $city) {
            $city_name = $city->name_fa;
        }

        switch ($request->type) {
            case "1":
                $type_fa = 'دائمی';
                break;
            case "2":
                $type_fa = 'موقت';
                break;
            case "3":
                $type_fa = 'فصلی';
                break;
        }

        $create = RahdariPoint::create([
            'province_id' => $request->province_id,
            'province_name' => $province_name,
            'city_id' => $request->city_id,
            'city_name' => $city_name,
            'name' => $request->name,
            'status' => $request->status,
            'type' => $request->type,
            'type_fa' => $type_fa,
            'team_num' => $request->team_num,
            'staff_num' => $request->staff_num,
            'phone' => $request->phone,
            'responsible_name' => $request->responsible_name,
            'responsible_mobile' => $request->responsible_mobile,
            'successor_name' => $request->successor_name,
            'successor_mobile' => $request->successor_mobile,
            'machines_light' => $request->machines_light,
            'machines_sheavy' => $request->machines_sheavy,
            'machines_heavy' => $request->machines_heavy,
            'code' => $request->code,
            'lat' => $request->lat,
            'lng' => $request->lng,
            'updated_at_fa' => Verta::now()->format('Y/m/d H:i:s'),
        ]);


        if ($request->has('overview_files_1')) {
            $file1 = $request->file('overview_files_1')->store('rahdari_points/overview', 'public');
            $create->files()->create(['path' => $file1]);
        }

        if ($request->has('overview_files_2')) {
            $file2 = $request->file('overview_files_2')->store('rahdari_points/overview', 'public');
            $create->files()->create(['path' => $file2]);
        }

        if ($request->has('overview_files_3')) {
            $file3 = $request->file('overview_files_3')->store('rahdari_points/overview', 'public');
            $create->files()->create(['path' => $file3]);
        }

        if ($request->has('overview_files_4')) {
            $file4 = $request->file('overview_files_4')->store('rahdari_points/overview', 'public');
            $create->files()->create(['path' => $file4]);
        }

        if ($request->has('overview_files_5')) {
            $file5 = $request->file('overview_files_5')->store('rahdari_points/overview', 'public');
            $create->files()->create(['path' => $file5]);
        }
        $new = RahdariPoint::where('id', $create->id)->with('files')->get();
        return response()->json([
            'message' => 'success',
            'data' => $new
        ]);
    }

    public function update(Request $request, $id)
    {
        /// [START] tollhouse_edit_data_update
        if (!(Auth::user()->can('edit-tollhouse') || Auth::user()->can('edit-tollhouse-province') )) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] tollhouse_edit_data_update
        
        
        $point = RahdariPoint::find($id);
        
        \App\Models\RahdariPointHistory::create([
            'user_id' => auth()->user()->id,
            'previous_status' => $point->status,
            'previous_type' => $point->type,
            'previous_team_num' => $point->team_num,
            'previous_staff_num' => $point->staff_num,
            'previous_phone' => $point->phone,
            'previous_responsible_name' => $point->responsible_name,
            'previous_responsible_mobile' => $point->responsible_mobile,
            'previous_successor_name' => $point->successor_name,
            'previous_successor_mobile' => $point->successor_mobile,
            'previous_machines_light' => $point->machines_light,
            'previous_machines_sheavy' => $point->machines_sheavy,
            'previous_machines_heavy' => $point->machines_heavy,
            'previous_lat' => $point->lat,
            'previous_lng' => $point->lng,
            'point_id' => $point->id,
            'new_files' => json_encode($point->files)
        ]);

        switch ($request->type) {
            case "1":
                $type_fa = 'دائمی';
                break;
            case "2":
                $type_fa = 'موقت';
                break;
            case "3":
                $type_fa = 'فصلی';
                break;
        }
        
        $point->status = $request->input('status') ?? $point->status;
        $point->type = $request->input('type') ?? $point->type;
        $point->type_fa = $type_fa ?? $point->type_fa;
        $point->team_num = $request->input('team_num') ?? $point->team_num;
        $point->staff_num = $request->input('staff_num') ?? $point->staff_num;
        $point->phone = $request->input('phone') ?? $point->phone;
        $point->responsible_name = $request->input('responsible_name') ?? $point->responsible_name;
        $point->responsible_mobile = $request->input('responsible_mobile') ?? $point->responsible_mobile;
        $point->successor_name = $request->input('successor_name') ?? $point->successor_name;
        $point->successor_mobile = $request->input('successor_mobile') ?? $point->successor_mobile;
        $point->machines_light = $request->input('machines_light') ?? $point->machines_light;
        $point->machines_sheavy = $request->input('machines_sheavy') ?? $point->machines_sheavy;
        $point->machines_heavy = $request->input('machines_heavy') ?? $point->machines_heavy;
        $point->lat = $request->input('lat') ?? $point->lat;
        $point->lng = $request->input('lng') ?? $point->lng;
        $point->lat_from = $request->input('lat-from') ?? null;
        $point->lng_from = $request->input('lng-from') ?? null;
        $point->geometry = $request->input('geometry') ?? null;
        $point->lat_to = $request->input('lat-to') ?? null;
        $point->lng_to = $request->input('lng-to') ?? null;
        $point->color = $request->input('color') ?? null;
        $point->updated_at_fa = Verta::now()->format('Y/m/d H:i:s');
        $point->save();

        if ($request->has('overview_files_1')) {
            if (isset($point->files[0])) {
                if(\File::exists('storage/'.$point->files[0]->path)){
                    \File::delete('storage/'.$point->files[0]->path);
                }
                $file = $request->file('overview_files_1')->store('rahdari_points/overview', 'public');
                $point->files[0]->update(['path' => $file]); 
            }else{
                $file1 = $request->file('overview_files_1')->store('rahdari_points/overview', 'public');
                $point->files()->create(['path' => $file1]);
            }
        }

        if ($request->has('overview_files_2')) {
            if (isset($point->files[1])) {
                if(\File::exists('storage/'.$point->files[1]->path)){
                    \File::delete('storage/'.$point->files[1]->path);
                }
                $file = $request->file('overview_files_2')->store('rahdari_points/overview', 'public');
                $point->files[1]->update(['path' => $file]); 
            }else{
                $file1 = $request->file('overview_files_2')->store('rahdari_points/overview', 'public');
                $point->files()->create(['path' => $file1]);
            }
        }

        if ($request->has('overview_files_3')) {
            if (isset($point->files[2])) {
                if(\File::exists('storage/'.$point->files[2]->path)){
                    \File::delete('storage/'.$point->files[2]->path);
                }
                $file = $request->file('overview_files_3')->store('rahdari_points/overview', 'public');
                $point->files[2]->update(['path' => $file]); 
            }else{
                $file1 = $request->file('overview_files_3')->store('rahdari_points/overview', 'public');
                $point->files()->create(['path' => $file1]);
            }
        }

        if ($request->has('overview_files_4')) {
            if (isset($point->files[3])) {
                if(\File::exists('storage/'.$point->files[3]->path)){
                    \File::delete('storage/'.$point->files[3]->path);
                }
                $file = $request->file('overview_files_4')->store('rahdari_points/overview', 'public');
                $point->files[3]->update(['path' => $file]); 
            }else{
                $file1 = $request->file('overview_files_4')->store('rahdari_points/overview', 'public');
                $point->files()->create(['path' => $file1]);
            }
        }

        if ($request->has('overview_files_5')) {
            if (isset($point->files[4])) {
                if(\File::exists('storage/'.$point->files[4]->path)){
                    \File::delete('storage/'.$point->files[4]->path);
                }
                $file = $request->file('overview_files_5')->store('rahdari_points/overview', 'public');
                $point->files[4]->update(['path' => $file]); 
            }else{
                $file1 = $request->file('overview_files_5')->store('rahdari_points/overview', 'public');
                $point->files()->create(['path' => $file1]);
            }
        }

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

    public function destroy($id)
    {
        /// [START] tollhouse_delete_data_delete
        if (! Auth::user()->can('delete-tollhouse')) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        } elseif (! Auth::user()->can('delete-tollhouse-province')) {
            return response()->json([
                'message' => 'Forbidden'
            ], 403);
        }
        /// [END] tollhouse_delete_data_delete
        
        \App\Models\RahdariPointHistory::where('point_id', $id)->delete();

        foreach (RahdariPoint::find($id)->files as $key => $value) {
            \File::delete('storage/'.$value->path);
        }

        RahdariPoint::find($id)->files()->delete();
        RahdariPoint::find($id)->delete();
        
        return response()->json([
            'message' => 'item is deleted.'
        ]);
    }
    
    public function get_road_toll_for_141(Request $request){
        if ($request->username == 'dfsklhkdljhfjkhlfh' and $request->password == 'sdflkjkdfhdlfjhgsdjhgf'){
            $data = RahdariPoint::select('id', 'type', 'type_fa', 'lat', 'lng', 'name', 'city_name','province_name', 'province_id')->get();
            return response()->json([
                'data'=> $data,
                'status' =>200
            ],200);
        }
        return response()->json([
            'status' => 401,
            'desc' => 'unathenticated'
        ],401);
    }
}