<?php

namespace App\Http\Controllers\V3\Dashboard;

use App\Enums\RoadMaintenanceStationTypes;
use App\Facades\DataTable\DataTableFacade;
use App\Facades\File\FileFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\RoadMaintenanceStation\StoreRequest;
use App\Http\Requests\V3\RoadMaintenanceStation\UpdateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\City;
use App\Models\Province;
use App\Models\RahdariPoint;
use App\Models\RahdariPointHistory;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;


class RoadMaintenanceStationController extends Controller
{
    use ApiResponse;

    public function index(Request $request): JsonResponse
    {
        $user = auth()->user();
        auth()->user()->addActivityComplete(1019);

        $allowedFilters = ['*'];
        $allowedSortings = ['*'];

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

        $query = RahdariPoint::query()
            ->when($status, fn ($query, $status) => $query->where('status', $status))
            ->when($type, fn ($query, $type) => $query->where('type', $type))
            ->when($province, fn($query, $province) => $query->where('province_id', $province));

        if ($user->hasPermissionTo('show-tollhouse-province')) {
            $query->where('province_id', $user->province_id);
        }

        $data = DataTableFacade::run(
            $query,
            $request,
            allowedFilters: $allowedFilters,
            allowedSortings: $allowedSortings
        );


        foreach ($data['data'] as &$stations) {
            if ($user->hasPermissionTo('edit-tollhouse')) {
                $stations['canEdit'] = 1;
            }
            elseif ($user->hasPermissionTo('edit-tollhouse-province') && $stations->province_id == $user->province_id) {
                $stations['canEdit'] = 1;
            }
            else {
                $stations['canEdit'] = 0;
            }

            if ($user->hasPermissionTo('delete-tollhouse')) {
                $stations['canDelete'] = 1;
            }
            elseif ($user->hasPermissionTo('delete-tollhouse-province') && $stations->province_id == $user->province_id) {
                $stations['canDelete'] = 1;
            }
            else {
                $stations['canDelete'] = 0;
            }
        }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreRequest $request): JsonResponse
    {
        $province = Province::query()->find($request->province_id);

        $city = City::query()->find($request->city_id);

        $station = RahdariPoint::query()->create([
            'province_id' => $province->id,
            'province_name' => $province->name_fa,
            'city_id' => $city->id,
            'city_name' => $city->name_fa,
            'name' => $request->name,
            'status' => $request->status,
            'type' => $request->type,
            'type_fa' =>RoadMaintenanceStationTypes::name($request->type),
            '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'),
        ]);

        $uploadPaths = [
            'overview_files_1' => "road_stations/{$station->id}",
            'overview_files_2' => "road_stations/{$station->id}",
            'overview_files_3' => "road_stations/{$station->id}",
            'overview_files_4' => "road_stations/{$station->id}",
            'overview_files_5' => "road_stations/{$station->id}",
        ];

        foreach ($uploadPaths as $field => $path) {
            if ($request->hasFile($field)) {
                $station->files()->create([
                    'path' => FileFacade::save($request->$field, $path)
                ]);
            }
        }

        return $this->successResponse();
    }

    /**
     * Display the specified resource.
     */
    public function show(RahdariPoint $rahdariPoint): JsonResponse
    {
        return $this->successResponse($rahdariPoint->load('files'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateRequest $request, RahdariPoint $rahdariPoint): JsonResponse
    {
        $province = Province::query()->find($request->province_id);

        $city = City::query()->find($request->city_id);

        RahdariPointHistory::query()->create([
            'user_id' => $request->user()->id,
            'point_id' =>  $rahdariPoint->id,
            'previous_province_id' => $province->id,
            'previous_province_name' => $province->name_fa,
            'previous_city_id' => $city->id,
            'previous_city_name' => $city->name_fa,
            'previous_name' =>   $rahdariPoint->name,
            'previous_status' =>  $rahdariPoint->status,
            'previous_type' =>  $rahdariPoint->type,
            'previous_team_num' => $rahdariPoint->team_num,
            'previous_staff_num' => $rahdariPoint->staff_num,
            'previous_phone' =>  $rahdariPoint->phone,
            'previous_responsible_name' => $rahdariPoint->responsible_name,
            'previous_responsible_mobile' => $rahdariPoint->responsible_mobile,
            'previous_successor_name' => $rahdariPoint->successor_name,
            'previous_successor_mobile' => $rahdariPoint->successor_mobile,
            'previous_machines_light' => $rahdariPoint->machines_light,
            'previous_machines_sheavy' => $rahdariPoint->machines_sheavy,
            'previous_machines_heavy' => $rahdariPoint->machines_heavy,
            'previous_lat' =>  $rahdariPoint->lat,
            'previous_lng' =>  $rahdariPoint->lng,
            'new_files' => json_encode($rahdariPoint->files),
        ]);

         $rahdariPoint->update([
            'province_id' => $province->id,
            'province_name' => $province->name_fa,
            'city_id' => $city->id,
            'city_name' => $city->name_fa,
            'name' => $request->input('name'),
            'status' => $request->input('status'),
            'type' => $request->input('type',),
            'type_fa' => RoadMaintenanceStationTypes::name($request->type) ??  $rahdariPoint->type_fa,
            'team_num' => $request->input('team_num'),
            'staff_num' => $request->input('staff_num'),
            'phone' => $request->input('phone'),
            'responsible_name' => $request->input('responsible_name'),
            'responsible_mobile' => $request->input('responsible_mobile'),
            'successor_name' => $request->input('successor_name'),
            'successor_mobile' => $request->input('successor_mobile'),
            'machines_light' => $request->input('machines_light'),
            'machines_sheavy' => $request->input('machines_sheavy'),
            'machines_heavy' => $request->input('machines_heavy'),
            'lat' => $request->input('lat'),
            'lng' => $request->input('lng'),
            'lat_from' => $request->lat_from,
            'lng_from' => $request->lng_from,
            'geometry' => $request->geometry,
            'lat_to' => $request->lat_to,
            'lng_to' => $request->lng_to,
            'color' => $request->color,
            'updated_at_fa' => verta()->now()->format('Y/m/d H:i:s'),
        ]);

        $uploadFields = [
            'overview_files_1',
            'overview_files_2',
            'overview_files_3',
            'overview_files_4',
            'overview_files_5',
        ];

        foreach ($uploadFields as $index => $field) {
            if ($request->hasFile($field)) {
                $existingFile = $rahdariPoint->files->get($index);
                $path = FileFacade::save($request->$field, "road_stations/{$rahdariPoint->id}");

                if ($existingFile) {
                    FileFacade::delete($existingFile->path);
                    $existingFile->update(['path' => $path]);
                } else {
                    $rahdariPoint->files()->create(['path' => $path]);
                }
            }
        }

        return $this->successResponse();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(RahdariPoint $rahdariPoint): JsonResponse
    {
        foreach ($rahdariPoint->files as $file) {
            FileFacade::delete($file->path);
        }
        $rahdariPoint->rahdariPointHistories()->delete();
        $rahdariPoint->files()->delete();
        $rahdariPoint->delete();

        return $this->successResponse();
    }

    public function images(RahdariPoint $rahdariPoint): JsonResponse
    {
        return $this->successResponse($rahdariPoint->files()->orderBy('id')->get(['path']));
    }

    public function map(Request $request): JsonResponse
    {
        auth()->user()->addActivityComplete(1023);

        return response()->json(DataTableFacade::run(
            RahdariPoint::query(),
            $request,
            allowedFilters: ['*'],
            allowedSortings: ['*'],
            allowedSelects: ['id', 'lat', 'lng', 'status', 'type'],
        ));
    }
}
