<?php

namespace App\Http\Controllers\V2\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\RoadObservationHistory;
use App\Models\RoadObserved;
use App\Models\City;
use App\Models\User;
use App\Models\EdarateShahri;
use App\Models\Contractor;
use Illuminate\Support\Facades\Validator;
use App\Models\SafetyAndPrivacy;
use App\Services\NominatimService;
use App\Models\InfoItem;

class SafetyAndPrivacyController extends Controller
{
    public function operatorCartable()
    {
        if (! auth()->user()->hasAnyPermission(['show-safety-and-privacy-operator-cartable', 'show-safety-and-privacy-operator-cartable-province', 'show-safety-and-privacy-operator-cartable-edarate-shahri'])) {
            abort(403);
        }
        auth()->user()->addActivityComplete(1133);

        return view('version2.dashboard_pages.safety_and_privacy.operation_cartable');
    }

    public function operatorShow(Request $request)
    {
        if (! auth()->user()->hasAnyPermission(['show-safety-and-privacy-operator-cartable', 'show-safety-and-privacy-operator-cartable-province', 'show-safety-and-privacy-operator-cartable-edarate-shahri'])) {
            abort(403);
        }

        $fields = ['id','lat','lon','province_id','province_fa','city_id','city_fa','edare_shahri_id','edare_shahri_name',
                   'recognize_picture','action_picture','operator_id','operator_name','way_id','created_at','updated_at','step','judiciary_document',
                   'judiciary_document_upload_date','info_id','info_fa','activity_date_time','judiciary_document_upload_date','action_picture_document_upload_date',
                   'step_fa'];

        $aliases = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '','','','','','','','','',''];

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

        if (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable')) {
            $query = SafetyAndPrivacy::selectRaw($selectRaw);
        } elseif (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = SafetyAndPrivacy::where('province_id', auth()->user()->province_id)
                                 ->selectRaw($selectRaw);
        } elseif (auth()->user()->hasPermissionTo('show-safety-and-privacy-operator-cartable-edarate-shahri')) {
            if (is_null(auth()->user()->edarate_shahri_id)) {
                return response()->json([
                    'message' => 'اداره ای برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = SafetyAndPrivacy::where('edare_shahri_id', auth()->user()->edarate_shahri_id)
                                 ->selectRaw($selectRaw);
        }

        $data = processDataTable($request, '', $fields, $query);

        return response()->json(
            $data,
        );
    }

    public function operatorFirstStepView()
    {
        if (! auth()->user()->hasAnyPermission(['add-safety-and-privacy'])) {
            abort(403);
        }

        return view('version2.dashboard_pages.safety_and_privacy.operation_create');
    }

    public function operatorFirstStepStore(Request $request, NominatimService $nominatimService)
    {
        if (! auth()->user()->hasAnyPermission(['add-safety-and-privacy'])) {
            abort(403);
        }

        if (Auth::user()->edarate_ostani_id || is_null(Auth::user()->city_id)) {
            return response()->json([
                        'message' => 'امکان ثبت این مورد برای ادارات استانی و ستادی وجود ندارد!'
                    ], 400);
        }

        if (is_null(Auth::user()->edarate_shahri_id)) {
            return response()->json([
                'message' => 'اداره شهری برای شما در سامانه ثبت نشده است!'
            ], 400);
        }

        $validator = Validator::make($request->all(), [
            'point' => 'required',
            'info_id' => 'required',
            'activity_date' => 'required|date_format:Y-m-d',
            'activity_time' => 'required|date_format:H:i',
            'recognize_picture' => 'required|image',

        ], [], [
            'activity_date' => 'تاریخ فعالیت',
            'activity_time' => 'ساعت فعالیت',
        ])->validate();

        $coordinates = explode(',', $request->point);
        $item = InfoItem::where('id', $request->info_id)->where('item', 17)->firstOrFail();

        try {
            $safety_and_privacy = \DB::transaction(function () use ($request, $coordinates, $item, $nominatimService) {
                $safety_and_privacy = SafetyAndPrivacy::create([
                    'lat' => $coordinates[0],
                    'lon' => $coordinates[1],
                    'operator_id' => auth()->user()->id,
                    'operator_name' => auth()->user()->name,
                    'province_id' => auth()->user()->province_id,
                    'province_fa' => auth()->user()->province_fa,
                    'info_id' => $item->id,
                    'info_fa' => $item->sub_item_str,
                    'city_id' => auth()->user()->city_id,
                    'city_fa' => auth()->user()->city_fa,
                    'activity_date_time' => $request->activity_date." ".$request->activity_time,
                    'edare_shahri_id' => auth()->user()->edarate_shahri_id,
                    'edare_shahri_name' => auth()->user()->edarate_shahri_name,
                    'way_id' => $nominatimService->get_way_id_from_nominatim($coordinates[0], $coordinates[1]),
                ]);

                if ($request->has('recognize_picture')) {
                    $recognize_picture = $request->file('recognize_picture')->store('safety_and_privacy/'.$safety_and_privacy->id.'/recognize_picture', 'public');
                    $safety_and_privacy->recognize_picture = Storage::disk('public')->url($recognize_picture);
                    // \App\Helpers\Compress::resize("/var/www/rms/public/storage/{$recognize_picture}");
                }

                $safety_and_privacy->goToFirstStep();
                $safety_and_privacy->save();
                auth()->user()->addActivityComplete(1134);
            });
        } catch (\Throwable $th) {
            $th->getMessage();
            throw $th;
        }

        return response()->json([
            'safety_and_privacy_id' => $safety_and_privacy,
            'message' => 'succussful'
        ]);
    }

    public function operatorSecondStepStore(SafetyAndPrivacy $safety_and_privacy, Request $request)
    {
        if (! auth()->user()->hasAnyPermission(['add-safety-and-privacy'])) {
            abort(403);
        }

        if (Auth::user()->edarate_ostani_id || is_null(Auth::user()->city_id)) {
            return response()->json([
                'message' => 'امکان ثبت این مورد برای ادارات استانی و ستادی وجود ندارد!'
            ], 400);
        }

        if (is_null(Auth::user()->edarate_shahri_id)) {
            return response()->json([
                'message' => 'اداره شهری برای شما در سامانه ثبت نشده است!'
            ], 400);
        }

        $validator = Validator::make($request->all(), [
            'judiciary_document' => 'required|array',
            'judiciary_document.*' => 'file',
        ])->validate();

        try {
            \DB::transaction(function () use ($request, $safety_and_privacy) {
                $judiciary_document = [];
                foreach ($request->judiciary_document as $index => $item) {
                    $judiciary_document[] = $temp = $item->store('safety_and_privacy/'.$safety_and_privacy->id.'/judiciary_document', 'public');
                }
                $safety_and_privacy->judiciary_document = serialize($judiciary_document);
                $safety_and_privacy->judiciary_document_upload_date = now();

                $safety_and_privacy->goToSecondStep();
                $safety_and_privacy->save();

                auth()->user()->addActivityComplete(1135);
            });
        } catch (\Throwable $th) {
            throw $th;
        }

        return response()->json([
            'safety_and_privacy_id' => $safety_and_privacy,
            'message' => 'succussful'
        ]);
    }

    public function operatorThirdStepStore(SafetyAndPrivacy $safety_and_privacy, Request $request)
    {
        if (! auth()->user()->hasAnyPermission(['add-safety-and-privacy'])) {
            abort(403);
        }

        if (Auth::user()->edarate_ostani_id || is_null(Auth::user()->city_id)) {
            return response()->json([
                'message' => 'امکان ثبت این مورد برای ادارات استانی و ستادی وجود ندارد!'
            ], 400);
        }

        if (is_null(Auth::user()->edarate_shahri_id)) {
            return response()->json([
                'message' => 'اداره شهری برای شما در سامانه ثبت نشده است!'
            ], 400);
        }

        $validator = Validator::make($request->all(), [
            'action_picture' => 'required|image',
        ])->validate();

        try {
            \DB::transaction(function () use ($request, $safety_and_privacy) {
                $action_picture = $request->file('action_picture')->store('safety_and_privacy/'.$safety_and_privacy->id.'/action_picture', 'public');
                $safety_and_privacy->action_picture = Storage::disk('public')->url($action_picture);
                // \App\Helpers\Compress::resize("/var/www/rms/public/storage/{$action_picture}");
                $safety_and_privacy->action_picture_document_upload_date = now();

                $safety_and_privacy->goToThirdStep();
                $safety_and_privacy->save();
                auth()->user()->addActivityComplete(1136);
            });
        } catch (\Throwable $th) {
            throw $th;
        }

        return response()->json([
            'safety_and_privacy_id' => $safety_and_privacy,
            'message' => 'succussful'
        ]);
    }

    public function unserialize(SafetyAndPrivacy $safety_and_privacy)
    {
        $datas = isset($safety_and_privacy->judiciary_document) ? unserialize($safety_and_privacy->judiciary_document) : [];

        $result = [];

        foreach ($datas as $data) {
            $result[] = Storage::disk('public')->url($data);
        }

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

    public function subItemList()
    {
        return response()->json([
            'data' => InfoItem::where('item', 17)->select('id', 'item', 'item_str', 'sub_item_str as name', 'sub_item_unit as unit', 'needs_image', 'needs_end_point', 'sub_item')->get()
        ]);
    }

    public function getAllDataToMap(Request $request)
    {
        $province = $request->province_id;
        $edare_shahri = $request->edare_shahri_id;
        $step = $request->step;
        $info_id = $request->info_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('safety_and_privacy')
                    ->when($province, function ($query, $province) {
                        return $query->where('province_id', $province);
                    })
                    ->when($edare_shahri, function ($query, $edare_shahri) {
                        return $query->where('edare_shahri_id', $edare_shahri);
                    })
                    ->when($step, function ($query, $step) {
                        return $query->where('step', $step);
                    })
                    ->when($info_id, function ($query, $info_id) {
                        return $query->where('info_id', $info_id);
                    })
                    ->whereBetween('created_at', [
                        $date_from,
                        $date_to,
                    ])
                    ->select('id', 'lat', 'lon', 'step')
                    ->get();

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

    public function detail(SafetyAndPrivacy $safety_and_privacy)
    {
        return response()->json($safety_and_privacy, 200);
    }

    public function delete(Request $request, SafetyAndPrivacy $safety_and_privacy)
    {
        if (!auth()->user()->can('delete-road-item')) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        Storage::deleteDirectory('public/' . 'safety_and_privacy/' . $safety_and_privacy->id);

        auth()->user()->addActivityComplete(1155);

        $safety_and_privacy->delete();

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