<?php

namespace App\Http\Controllers\V2\Dashboard;

use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\RoadItemsProject;
use App\Models\EdarateShahri;
use App\Models\ObservedItem;
use App\Models\InfoItem;
use App\Services\NominatimService;
use App\Exports\V2\RoadItems\OperatorCartableExport;
use App\Exports\V2\RoadItems\SupervisorCartableExport;

class RoadItemsProjectController extends Controller
{
    /**
     * Supervisor(Begin)
     */
    public function supervisorCartable()
    {
        if (!auth()->user()->can('show-road-item-supervise-cartable')
            && !auth()->user()->can('show-road-item-supervise-cartable-province')) {
            abort(403);
        }

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

        return view('version2.dashboard_pages.road_items.supervise_cartable');
    }

    public function supervisorShow(Request $request)
    {
        $fields = ['id', 'user_id', 'start_lat', 'start_lng', 'end_lat', 'end_lng', 'project_distance', 'item', 'item_fa', 'sub_item_fa', 'sub_item_data',
                   'created_at', 'updated_at', 'province_id', 'province_fa',
                   'unit_fa', 'status', 'status_fa', 'supervisor_description', 'supervising_time', 'supervisor_name', 'edarat_id', 'edarat_name', 'activity_date_time'];

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

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

        if (auth()->user()->can('show-road-item-supervise-cartable')) {
            $query = RoadItemsProject::where('is_new', 1)
            ->with('files')
            // ->where(function ($query) {
            //     $query->where('status', 0);
            // })
            ->selectRaw($selectRaw);
        } elseif (auth()->user()->can('show-road-item-supervise-cartable-province')) {
            if (is_null(auth()->user()->province_id)) {
                return response()->json([
                    'message' => 'استانی برای شما در سامانه ثبت نشده است!'
                ], 400);
            }

            $query = RoadItemsProject::where('is_new', 1)->with('files')->where('province_id', auth()->user()->province_id)
                                    //  ->where(function ($query) {
                                    //      $query->where('status', 0)
                                    //          ->orWhere('supervisor_id', auth()->user()->id);
                                    //  })
                                     ->selectRaw($selectRaw);
        } else {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        $road_items = processDataTable($request, '', $fields, $query);
        $road_items['data']->map(function ($road_item) {
            if (Gate::allows('gate-supervise-road-item', $road_item)) {
                $road_item['can_supervise'] = 1;
            } else {
                $road_item['can_supervise'] = 0;
            }
        });

        return response()->json(
            $road_items,
            $road_items['status'],
        );
    }

    public function verifyBySupervisor(Request $request, RoadItemsProject $road_item)
    {
        if (Gate::allows('gate-supervise-road-item', $road_item)) {
            $request->validate([
                'verify' => 'required|in:1,2',
                'description' => 'nullable|string',
            ]);

            $status_fa = $request->verify == 1 ? 'تایید شده' : 'عدم تایید';
            $road_item->update([
                'status' => $request->verify,
                'status_fa' => $status_fa,
                'supervisor_id' => auth()->user()->id,
                'supervisor_name' => auth()->user()->name,
                'supervisor_description' => $request->description,
                'supervising_time' => now(),
            ]);

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

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

        return response()->json([
            'message' => 'access to requested resource is forbidden.'
        ], 403);
    }

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

        if ($road_item->status == 0) {
            return response()->json([
                'message' => 'امکان بازگردانی وضعیت این فعالیت وجود ندارد!'
            ], 400);
        }

        $road_item->update([
            'status' => 0,
            'status_fa' => 'در حال بررسی',
            'supervisor_id' => null,
            'supervisor_description' => null,
            'supervising_time' => null,
            'supervisor_name' =>  null,
        ]);
        auth()->user()->addActivityComplete(1150);

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

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

        if ($road_item->files()->exists()) {
            Storage::delete('public/'. $road_item->files[0]->path);
            Storage::delete('public/'. $road_item->files[1]->path);
            $road_item->files()->delete();
        }
        auth()->user()->addActivityComplete(1151);

        $road_item->delete();

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


    public function supervisorCartableReport(Request $request)
    {
        $name = 'گزارش از کارتابل ارزیابی فعالیت روزانه ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        return Excel::download(new SupervisorCartableExport($request->id, $request->item, $request->status, 
                                                            $request->fromDate, $request->toDate, $request->province_id, $request->edarat_id), $name);
    }

    /**
     * Supervisor(End)
     */

    /**
     * Operator(Begin)
     */

    public function operatorCreateView()
    {
        if (!auth()->user()->can('create-road-item')) {
            abort(403);
        }

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

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

    public function operatorCartable()
    {
        if (!auth()->user()->can('create-road-item')) {
            abort(403);
        }

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

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

    public function store(Request $request, NominatimService $nominatimService)
    {
        if (!Auth::user()->can('create-road-item')) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 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(), [
            'start_point' => 'required',
            'item_id' => 'required|integer',
            'sub_item_id' => 'required|integer',
            'amount' => 'required|numeric',
            // 'project_distance' => 'numeric',
            'before_image' => 'image|max:4096',
            'after_image' => 'image|max:4096',
            'observed_item_id' => 'integer|exists:observed_items,id',
            'activity_date' => 'required|date_format:Y-m-d',
            'activity_time' => 'required|date_format:H:i',
        ], [], [
            'activity_date' => 'تاریخ فعالیت',
            'activity_time' => 'ساعت فعالیت',
        ])->validate();

        $info_item = InfoItem::where('item', $request->item_id)
                                         ->where('sub_item', $request->sub_item_id)
                                         ->firstOrFail();

        // $project_distance = null;
        if ($info_item->needs_end_point) {
            if (!$request->end_point) {
                throw ValidationException::withMessages([
                    'end_point' => __('validation.required', ['attribute' => 'end_point']),
                ]);
            }

            // if (!$request->project_distance) {
            //     throw ValidationException::withMessages([
            //         "project_distance" => __('validation.required', ['attribute' => 'project_distance']),
            //     ]);
            // }

            // $project_distance = $request->project_distance;
        }

        if ((!$request->before_image || !$request->after_image) && $info_item->needs_image) {
            throw ValidationException::withMessages([
                'before_image' => __('validation.required', ['attribute' => 'before_image']),
                'after_image' => __('validation.required', ['attribute' => 'after_image']),
            ]);
        }

        $start_coordinates = explode(',', $request->start_point);
        $end_coordinates = $info_item->needs_end_point ? explode(',', $request->end_point) : null;


        // prepare data array
        $attributes = [
            'start_lat' => $start_coordinates[0],
            'start_lng' => $start_coordinates[1],
            'end_lat' => $end_coordinates ? $end_coordinates[0] : null,
            'end_lng' => $end_coordinates ? $end_coordinates[1] : null,
            // 'project_distance' => $project_distance,
            'item' => $info_item->item,
            'item_fa' => $info_item->item_str,
            'sub_item' => $info_item->sub_item,
            'sub_item_fa' => $info_item->sub_item_str,
            'sub_item_data' => $request->amount,
            'province_id' => Auth::user()->province_id,
            'province_fa' => Auth::user()->province_fa,
            'city_id' => Auth::user()->city_id,
            'city_fa' => Auth::user()->city_fa,
            'user_name' => Auth::user()->name,
            'start_way_id' => $nominatimService->get_way_id_from_nominatim($start_coordinates[0], $start_coordinates[1]),
            'end_way_id' => $end_coordinates ? $nominatimService->get_way_id_from_nominatim($end_coordinates[0], $end_coordinates[1]) : null,
            'unit_fa' => $info_item->sub_item_unit,
            'created_at_fa' => verta(\Carbon\Carbon::now())->format('Y-m-d H:i:s'),
            'info_id' => $info_item->id,
            'status' => 0,
            'status_fa' => 'در حال بررسی',
            'edarat_id' => Auth::user()->edarate_shahri_id,
            'edarat_type' => EdarateShahri::class,
            'edarat_name' => Auth::user()->edarate_shahri_name,
            'activity_date' => $request->activity_date,
            'activity_time' => $request->activity_time,
        ];

        $before_image = null;
        $after_image = null;
        if ($info_item->needs_image) {
            if ($request->has('after_image')) {
                $after_image = $request->file('after_image');
            }
            if ($request->has('before_image')) {
                $before_image = $request->file('before_image');
            }
        }

        $road_item = RoadItemsProject::store(Auth::user(), $attributes, $before_image, $after_image, $request->observed_item_id);

        if ($road_item === -1) {
            return response()->json([
                'message' => 'اقدام مربوطه قبلا رسیدگی شده است.'
            ], 400);
        }
        auth()->user()->addActivityComplete(1154);

        return response()->json([
            'message' => 'succussful'
        ]);
    }

    public function update(Request $request, RoadItemsProject $road_item)
    {
        // can edit this item?
        if ($road_item->user_id != auth()->user()->id || $road_item->status != 2) {
            return response()->json([
                'message' => 'access to requested resource is forbidden.'
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'start_point' => 'required',
            'amount' => 'required|numeric',
            'before_image' => 'image|max:4096',
            'after_image' => 'image|max:4096',
        ])->validate();

        $info_item = InfoItem::where('item', $road_item->item)
                                         ->where('sub_item', $road_item->sub_item)
                                         ->firstOrFail();

        $start_coordinates = explode(',', $request->start_point);
        $end_coordinates = null;
        if ($info_item->needs_end_point) {
            if (!$request->end_point) {
                throw ValidationException::withMessages([
                    'end_point' => __('validation.required', ['attribute' => 'end_point']),
                ]);
            }

            $end_coordinates = explode(',', $request->end_point);
        }

        if ($info_item->needs_image) {
            if ($request->has('after_image')) {
                
                Storage::delete('public/'. $road_item->files[0]->path);

                $after = $request->file('after_image')->store('road_items_projects_new/after', 'public');
                $road_item->files[0]->update([
                    'path' => $after
                ]);
                // $road_item->files()->create(['path' => $after]);
                $urlAfter = "/var/www/rms/public/storage/{$after}";
//                \App\Helpers\Compress::resize($urlAfter);
            }
            if ($request->has('before_image')) {
                Storage::delete('public/'. $road_item->files[1]->path);

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

        $road_item->update([
            'start_lat' => $start_coordinates[0],
            'start_lng' => $start_coordinates[1],
            'end_lat' => $end_coordinates ? $end_coordinates[0] : null,
            'end_lng' => $end_coordinates ? $end_coordinates[1] : null,
            'sub_item_data' => $request->amount,
            'status' => 0,
            'status_fa' => 'در حال بررسی',
            // 'supervisor_id' => null,
            // 'supervisor_description' => null,
            // 'supervising_time' => null,
            // 'supervisor_name' =>  null,
        ]);


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

        return response()->json([
            'message' => 'succussful'
        ]);
    }

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

        $fields = ['id', 'user_id', 'start_lat', 'start_lng', 'end_lat', 'end_lng', 'project_distance', 'item', 'item_fa', 'sub_item_fa', 'sub_item_data',
                   'created_at', 'updated_at', 'province_id', 'province_fa',
                   'unit_fa', 'status', 'status_fa', 'supervisor_description', 'supervising_time', 'supervisor_name', 'edarat_id', 'edarat_name', 'activity_date_time'];

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

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

        $query = RoadItemsProject::with('files')
                                 ->where('is_new', 1)
                                 ->where('user_id', auth()->user()->id)
                                 ->selectRaw($selectRaw);

        $data = processDataTable($request, '', $fields, $query);
        return response()->json(
            $data,
            $data['status'],
        );
    }

    public function operatorCartableReport(Request $request)
    {
        $name = 'گزارش از کارتابل عملیات فعالیت روزانه ' . verta()->now()->format('Y-m-d H:i') . '.xlsx';
        return Excel::download(new OperatorCartableExport($request->id, $request->item, $request->status, $request->fromDate, $request->toDate), $name);
    }

    /**
     * Operator(End)
     */

}
