<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Contracts;
use App\Models\ContractSubItems;
use App\Models\ContractSubItemsHistory;
use App\Models\Province;
use App\Models\RoadDangerPrevention;
use App\Models\RoadMaintenanceProject;
use App\Models\RoadTechnicalBuilding;
use App\Models\RoadTollhouseManagement;
use App\Models\RoadUpgradeSafety;
use Illuminate\Http\Request;
use Hekmatinasser\Verta\Verta;
use Illuminate\Support\Facades\DB;
use SoapClient;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\Facades\Sms\Sms;
use App\Services\NominatimService;
use Illuminate\Support\Str;

class ContractSubItemsController extends Controller
{
    public function getMaintenanceProject($id)
    {
        $roadProject = RoadMaintenanceProject::find($id);
        $roadProjectHistories = $roadProject->projectHistories;

        $roadProjectHistoriesFiles = [];
        $imagesIndex = 0;

        foreach ($roadProjectHistories as $key => $roadProjectHistory) {
            foreach ($roadProjectHistory->files as $keyPath => $file) {
                $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                $imagesIndex++;
            }
        }

        $cities = [];
        $citiesIndex = 0;

        foreach ($roadProject->cities_id as $cityKey => $value) {
            $getCity = \App\Models\City::find($cityKey);

            $cities[$citiesIndex] = [
                'id' => $getCity->id,
                'name' => $getCity->name_fa,
                'value' =>  $value
            ];

            $citiesIndex++;
        }

        $roadProjectArray = [
            'id' => $roadProject->id,
            'province' => [
                'id' => ($roadProject->province) ? $roadProject->province->id : null,
                'name' => ($roadProject->province) ? $roadProject->province->name_fa : '-',
                'lat_lng' => [
                    $roadProject->province->center_lat,
                    $roadProject->province->center_long
                ]
            ],
            'cities' => $cities,
            'axis_name' => ($roadProject->axis_name) ? $roadProject->axis_name : '-',
            'axis_type' => ($roadProject->axis_type) ?: 0,
            'project_name' => ($roadProject->project_name) ? $roadProject->project_name : '-',
            'contractor_name' => ($roadProject->contractor_name) ? $roadProject->contractor_name : '-',
            'consultant_name' => ($roadProject->consultant_name) ? $roadProject->consultant_name : '-',
            'contract_date' => ($roadProject->contract_date) ? $roadProject->contract_date : '-',
            'contract_credit' => ($roadProject->contract_credit) ? $roadProject->contract_credit : '-',
            'submited_at' => ($roadProject->submited_at) ?
                verta($roadProject->submited_at)->format('Y/n/j - H:i') : '-',
            'last_updated_at' => ($roadProject->last_updated_at) ?
                verta($roadProject->last_updated_at)->format('Y/n/j - H:i') : '-',
            'start_latlng' => $roadProject->start_latlng,
            'end_latlng' => $roadProject->end_latlng,
            'project_distance' => $roadProject->project_distance,
            'project_distance_update' => $roadProject->project_distance_update,
            'physical_progress' => $roadProject->physical_progress,
            'images' => $roadProjectHistoriesFiles,
            'project_status' => $roadProject->project_status
        ];

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

    public function ContractSubItemsList()
    {
        return response()->json([
           'message' => 'success',
           'data' => ContractSubItems::all()
        ]);
    }

    public function storeForDevelop(Request $request, NominatimService $nominatimService)
    {

        if ($request->has('operation_type_id1') && $request->operation_type_progress1 == null) {
            return response()->json(['message' => 'Operation type progress1 is NULL'], 400);
        }

        if ($request->has('operation_type_id2') && $request->operation_type_progress2 == null) {
            return response()->json(['message' => 'Operation type progress2 is NULL'], 400);
        }

        if ($request->has('operation_type_id3') && $request->operation_type_progress3 == null) {
            return response()->json(['message' => 'Operation type progress3 is NULL'], 400);
        }

        if ($request->has('operation_type_id4') && $request->operation_type_progress4 == null) {
            return response()->json(['message' => 'Operation type progress4 is NULL'], 400);
        }
        
        DB::beginTransaction();

        try {
            $data = $this->getOperationType($request, $request->project_type_id);

            if ($request->operation_type_id1) {
                $operation1 = $data[$request->operation_type_id1];
            }
            if ($request->operation_type_id2) {
                $operation2 = $data[$request->operation_type_id2];
            }
            if ($request->operation_type_id3) {
                $operation3 = $data[$request->operation_type_id3];
            }


            $contract = Contracts::where('id', $request->contract_id)->first();
            $parent_contract_date = explode('-', $contract->contract_date);
            // dd(Verta::jalaliToGregorian($parent_contract_date[0], $parent_contract_date[1], $parent_contract_date[2]));
            $parent_contract_date = Verta::jalaliToGregorian($parent_contract_date[0], $parent_contract_date[1], $parent_contract_date[2]);

            $city_fa = City::where('id', $request->city_id)->first();
            $province_fa = Province::where('id', $request->province_id)->first();


            /// switches
            $progress_project = ContractSubItems::checkProgressProjectCondition($request->last_status_id, $request->progress_project);

            $contractSubItem = new ContractSubItems();
            $contractSubItem->project_title = $request->project_title;
            $contractSubItem->project_type_id = $request->project_type_id;
            $contractSubItem->setProjectTypeFa($request->project_type_id);
            $contractSubItem->operation_type_id1 = $request->operation_type_id1 ?? null;
            $contractSubItem->operation_type_fa1 = $operation1['farsi'] ?? null;
            $contractSubItem->operation_type_unit1 = $operation1['unit'] ?? null;
            $contractSubItem->operation_type_amount1 = $request->operation_type_amount1 ?? null;
            $contractSubItem->operation_type_progress1 = $request->operation_type_progress1;
            $contractSubItem->operation_type_tonaj1 = $request->operation_type_tonaj1 ?? null;
            $contractSubItem->operation_type_id2 = $request->operation_type_id2 ?? null;
            $contractSubItem->operation_type_fa2 = $operation2['farsi'] ?? null;
            $contractSubItem->operation_type_unit2 = $operation2['unit'] ?? null;
            $contractSubItem->operation_type_amount2 = $request->operation_type_amount2 ?? null;
            $contractSubItem->operation_type_progress2 = $request->operation_type_progress2;
            $contractSubItem->operation_type_tonaj2 = $request->operation_type_tonaj2 ?? null;
            $contractSubItem->operation_type_id3 = $request->operation_type_id3 ?? null;
            $contractSubItem->operation_type_fa3 = $operation3['farsi'] ?? null;
            $contractSubItem->operation_type_unit3 = $operation3['unit'] ?? null;
            $contractSubItem->operation_type_amount3 = $request->operation_type_amount3 ?? null;
            $contractSubItem->operation_type_progress3 = $request->operation_type_progress3;
            $contractSubItem->operation_type_tonaj3 = $request->operation_type_tonaj3 ?? null;
            $contractSubItem->operation_type_id4 = $request->operation_type_id4 ?? null;
            $contractSubItem->operation_type_fa4 = $operation4['farsi'] ?? null;
            $contractSubItem->operation_type_unit4 = $operation4['unit'] ?? null;
            $contractSubItem->operation_type_amount4 = $request->operation_type_amount4 ?? null;
            $contractSubItem->operation_type_progress4 = $request->operation_type_progress4;
            $contractSubItem->operation_type_tonaj4 = $request->operation_type_tonaj4 ?? null;
            $contractSubItem->city_id = $request->city_id;
            $contractSubItem->city_fa = $city_fa->name_fa;
            $contractSubItem->province_id = $request->province_id;
            $contractSubItem->province_fa = $province_fa->name_fa;
            $contractSubItem->axis_type_id = $request->axis_type_id;
            $contractSubItem->setAxisTypeFa($request->axis_type_id);
            $contractSubItem->axis_name_fa = $request->axis_name_fa;
            $contractSubItem->start_lat = $request->start_lat;
            $contractSubItem->end_lat = $request->end_lat;
            $contractSubItem->start_lng = $request->start_lng;
            $contractSubItem->end_lng = $request->end_lng;
            $contractSubItem->followup_priority_project_id = $request->followup_priority_project_id;
            $contractSubItem->setFollowupPriorityProjectFa($request->followup_priority_project_id);
            $contractSubItem->priority_project = $request->priority_project;
            $contractSubItem->setPriorityProjectFa($request->priority_project);
            $contractSubItem->operator_name = $request->operator_name;
            $contractSubItem->operator_phone = $request->operator_phone;
            $contractSubItem->progress_project = $progress_project;
            $contractSubItem->last_status_id = $request->last_status_id;
            $contractSubItem->setLastStatusFa($request->last_status_id);
            $contractSubItem->last_digit_project = $request->last_digit_project;
            $contractSubItem->last_function_operator = $request->last_function_operator;
            $contractSubItem->last_payable_operator = $request->last_payable_operator;
            $contractSubItem->complete_payable = $request->complete_payable;
            $contractSubItem->contract_id = $request->contract_id;
            $contractSubItem->contract_date_from_parent_contract = $parent_contract_date[0].'-'.$parent_contract_date[1].'-'.$parent_contract_date[2];
            $contractSubItem->created_at_fa = Verta::instance(Verta::now());
            $contractSubItem->updated_at_fa = Verta::instance(Verta::now());
            $contractSubItem->start_way_id = $nominatimService->get_way_id_from_nominatim($request->start_lat, $request->start_lng);
            $contractSubItem->end_way_id = $nominatimService->get_way_id_from_nominatim($request->end_lat, $request->end_lng);
            $contractSubItem->user_id = Auth::user()->id;
            $contractSubItem->contract_moshaver_tarahi = $contract->contract_moshaver_tarahi;
            $contractSubItem->contract_moshaver_nezarat = $contract->contract_moshaver_nezarat;
            $contractSubItem->last_date_update = Carbon::now();

            $contractSubItem->required_bitumen = $request->required_bitumen ?? null;
            $contractSubItem->used_bitumen = $request->used_bitumen ?? null;

            $contractSubItem->bridge_number = $request->bridge_number ?? null;
            
            $contractSubItem->save();

            /// Generate Unique Code for this Contract Subitem
            $contractSubItem->unique_code = $contract->unique_id . '/' . $contractSubItem->id;
            $contractSubItem->save();

            if ($request->addNewSubitemStatus == 'false') {
                $projectQuery = ContractSubItems::getProjectQuery($request->project_type_id);
                $roadProject = $projectQuery->find($request->projectData_id);
                $roadProjectHistories = $roadProject->projectHistories;
                $roadProjectHistoriesFiles = [];
                $imagesIndex = 0;
                foreach ($roadProjectHistories as $key => $roadProjectHistory) {
                    foreach ($roadProjectHistory->files as $keyPath => $file) {
                        $roadProjectHistoriesFiles[$imagesIndex] = asset('storage' . substr($file->path, 6));
                        $imagesIndex++;
                    }
                }
                $roadProjectHistoriesFiles;
                $countRoadFiles = count($roadProjectHistoriesFiles);
            }

            $uuid = Str::uuid();
            if ($request->has('image1')) {
                $file1 = $request->file('image1');
                $destinationPath1 = 'storage/contract_subitems/' . now()->year . '/' . now()->month . '/';
                $filename1 = $uuid . '-one.' . $file1->getClientOriginalExtension();
                $file1->move($destinationPath1, $filename1);
                $contractSubItem->update(['image_path1' => $destinationPath1 . $filename1]);
            } elseif (! $request->has('image1') && $request->addNewSubitemStatus == 'false') {
                if ($countRoadFiles == 1) {
                    $countRoadFiles = 2;
                }

                $imageUrl = $roadProjectHistoriesFiles[$countRoadFiles - 2];
                if (strpos($imageUrl, "https://rms.rmto.ir/") == 0) {
                    $imageUrl = str_replace("https://rms.rmto.ir/", "", $imageUrl);
                }

                $contractSubItem->update(['image_path1' => $imageUrl ?? null ]);
            }

            if ($request->has('image2')) {
                $file2 = $request->file('image2');
                $destinationPath2 = 'storage/contract_subitems/' . now()->year . '/' . now()->month . '/';
                $filename2 = $uuid . '-two.' . $file2->getClientOriginalExtension();
                $file2->move($destinationPath2, $filename2);
                $contractSubItem->update(['image_path2' => $destinationPath2 . $filename2]);
            } elseif (! $request->has('image2') && $request->addNewSubitemStatus == 'false') {
                $contractSubItem->update(['image_path2' => $roadProjectHistoriesFiles[$countRoadFiles - 1] ?? null ]);
            }
            if ($request->addNewSubitemStatus == 'false') {
                $projectQuery->find($request->projectData_id)->projectHistories()->delete();
                $projectQuery->find($request->projectData_id)->delete();
            }

            $changeStatusRelInContracts = Contracts::find($request->contract_id);
            $changeStatusRelInContracts->status_rel = 2;
            $changeStatusRelInContracts->save();
            DB::commit();

            // send msg
            $msg = "سلام،\n پروژه راهداری با کد یکتای {$contractSubItem->unique_code} با مسئولیت شما در سامانه جامع راهداری ثبت شده است. لطفا به روز رسانی دقیق و به موقع پیشرفت پروژه در سامانه اولویت قرار گیرد.\n rms.rmto.ir";

            Sms::sendSms($contractSubItem->operator_phone, $msg);

            // self::sms_sender($contractSubItem->operator_phone, $msg);

            return response()->json([
                'message' => 'success',
                'data' => $contractSubItem
            ], 200);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json([
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function updateForDevelop(Request $request, $id, NominatimService $nominatimService)
    {
        if ($request->operation_type_id1 != 0 && $request->operation_type_progress1 == null) {
            return response()->json(['message' => 'Operation type progress1 is NULL'], 400);
        }
        if ($request->operation_type_id2 != 0 && $request->operation_type_progress2 == null) {
            return response()->json(['message' => 'Operation type progress2 is NULL'], 400);
        }
        if ($request->operation_type_id3 != 0 && $request->operation_type_progress3 == null) {
            return response()->json(['message' => 'Operation type progress3 is NULL'], 400);
        }
        if ($request->operation_type_id4 != 0 && $request->operation_type_progress4 == null) {
            return response()->json(['message' => 'Operation type progress4 is NULL'], 400);
        }

        $contractSubItem = ContractSubItems::find($id);

        $history = ContractSubItemsHistory::create([

            'project_title' => $contractSubItem->project_title,
            'project_type_id' => $contractSubItem->project_type_id,
            'project_type_fa' => $contractSubItem->project_type_fa,

            'operation_type_id1' => $contractSubItem->operation_type_id1 ?? null,
            'operation_type_fa1' => $contractSubItem->operation_type_fa1 ?? null,
            'operation_type_unit1' => $contractSubItem->operation_type_unit1 ?? null,
            'operation_type_amount1' => $contractSubItem->operation_type_amount1 ?? null,
            'operation_type_progress1' => $contractSubItem->operation_type_progress1 ?? null,
            'operation_type_tonaj1' => $contractSubItem->operation_type_tonaj1 ?? null,

            'operation_type_id2' => $contractSubItem->operation_type_id2 ?? null,
            'operation_type_fa2' => $contractSubItem->operation_type_fa2 ?? null,
            'operation_type_unit2' => $contractSubItem->operation_type_unit2 ?? null,
            'operation_type_amount2' => $contractSubItem->operation_type_amount2 ?? null,
            'operation_type_progress2' => $contractSubItem->operation_type_progress2 ?? null,
            'operation_type_tonaj2' => $contractSubItem->operation_type_tonaj2 ?? null,

            'operation_type_id3' => $contractSubItem->operation_type_id3 ?? null,
            'operation_type_fa3' => $contractSubItem->operation_type_fa3 ?? null,
            'operation_type_unit3' => $contractSubItem->operation_type_unit3 ?? null,
            'operation_type_amount3' => $contractSubItem->operation_type_amount3 ?? null,
            'operation_type_progress3' => $contractSubItem->operation_type_progress3 ?? null,
            'operation_type_tonaj3' => $contractSubItem->operation_type_tonaj3 ?? null,

            'operation_type_id4' => $contractSubItem->operation_type_id4 ?? null,
            'operation_type_fa4' => $contractSubItem->operation_type_fa4 ?? null,
            'operation_type_unit4' => $contractSubItem->operation_type_unit4 ?? null,
            'operation_type_amount4' => $contractSubItem->operation_type_amount4 ?? null,
            'operation_type_progress4' => $contractSubItem->operation_type_progress4 ?? null,
            'operation_type_tonaj4' => $contractSubItem->operation_type_tonaj4 ?? null,

            'city_id' => $contractSubItem->city_id,
            'city_fa' => $contractSubItem->city_fa,
            'province_id' => $contractSubItem->province_id,
            'province_fa' => $contractSubItem->province_fa,
            'axis_type_id' => $contractSubItem->axis_type_id,
            'axis_type_fa' => $contractSubItem->axis_type_fa,
            'axis_name_fa' => $contractSubItem->axis_name_fa,
            'start_lat' => $contractSubItem->start_lat,
            'end_lat' => $contractSubItem->end_lat,
            'start_lng' => $contractSubItem->start_lng,
            'end_lng' => $contractSubItem->end_lng,
            'followup_priority_project' => $contractSubItem->followup_priority_project,
            'priority_project' => $contractSubItem->priority_project,
            'operator_name' => $contractSubItem->operator_name,
            'operator_phone' => $contractSubItem->operator_phone,

            'progress_project' => $contractSubItem->progress_project,
            'last_status_id' => $contractSubItem->last_status_id,
            'last_status_fa' => $contractSubItem->last_status_fa,
            'subitem_id' => $contractSubItem->id,
            'operation_type_progress1' => $contractSubItem->operation_type_progress1,
            'operation_type_progress2' => $contractSubItem->operation_type_progress2,
            'operation_type_progress3' => $contractSubItem->operation_type_progress3,
            'operation_type_progress4' => $contractSubItem->operation_type_progress4,
            'last_digit_project' => $contractSubItem->last_digit_project,
            'last_function_operator' => $contractSubItem->last_function_operator,
            'last_payable_operator' => $contractSubItem->last_payable_operator,
            'complete_payable' => $contractSubItem->complete_payable,
            'image_path1' => $contractSubItem->image_path1,
            'image_path2' => $contractSubItem->image_path2,
            'unique_code' => $contractSubItem->unique_code,
            'required_bitumen' => $contractSubItem->required_bitumen,
            'used_bitumen' => $contractSubItem->used_bitumen,
            'bridge_number' => $contractSubItem->bridge_number,
            'is_corrected' => 1,
            'updated_at_fa' => $contractSubItem->updated_at_fa,
            'last_date_update' => $contractSubItem->last_date_update,
            'created_at_fa' => Verta::instance(Verta::now()),
        ]);

        $data = $this->getOperationType($request, $request->project_type_id);

        if ($request->operation_type_id1) {
            $operation1 = $data[$request->operation_type_id1];
        }
        if ($request->operation_type_id2) {
            $operation2 = $data[$request->operation_type_id2];
        }
        if ($request->operation_type_id3) {
            $operation3 = $data[$request->operation_type_id3];
        }
        if ($request->operation_type_id4) {
            $operation4 = $data[$request->operation_type_id4];
        }

        $contract = Contracts::where('id', $request->contract_id)->first();

        $city_fa = City::where('id', $request->city_id)->first();
        $province_fa = Province::where('id', $request->province_id)->first();
        $progress_project = ContractSubItems::checkProgressProjectCondition($request->last_status_id, $request->progress_project);

        $contractSubItem->setProjectTypeFa($request->project_type_id);
        $contractSubItem->setAxisTypeFa($request->axis_type_id);
        $contractSubItem->setFollowupPriorityProjectFa($request->followup_priority_project_id);
        $contractSubItem->setPriorityProjectFa($request->priority_project);
        $contractSubItem->setLastStatusFa($request->last_status_id);

        $contractSubItem->project_title = $request->project_title;
        $contractSubItem->project_type_id = $request->project_type_id;
        $contractSubItem->operation_type_id1 = $request->operation_type_id1 ?? null;
        $contractSubItem->operation_type_fa1 = $operation1['farsi'] ?? null;
        $contractSubItem->operation_type_unit1 = $operation1['unit'] ?? null;
        $contractSubItem->operation_type_amount1 = $request->operation_type_amount1 ?? null;
        $contractSubItem->operation_type_progress1 = $request->operation_type_progress1 ?? null;
        $contractSubItem->operation_type_tonaj1 = $request->operation_type_tonaj1 ?? null;
        $contractSubItem->operation_type_id2 = $request->operation_type_id2 ?? null;
        $contractSubItem->operation_type_fa2 = $operation2['farsi'] ?? null;
        $contractSubItem->operation_type_unit2 = $operation2['unit'] ?? null;
        $contractSubItem->operation_type_amount2 = $request->operation_type_amount2 ?? null;
        $contractSubItem->operation_type_progress2 = $request->operation_type_progress2 ?? null;
        $contractSubItem->operation_type_tonaj2 = $request->operation_type_tonaj2 ?? null;
        $contractSubItem->operation_type_id3 = $request->operation_type_id3 ?? null;
        $contractSubItem->operation_type_fa3 = $operation3['farsi'] ?? null;
        $contractSubItem->operation_type_unit3 = $operation3['unit'] ?? null;
        $contractSubItem->operation_type_amount3 = $request->operation_type_amount3 ?? null;
        $contractSubItem->operation_type_progress3 = $request->operation_type_progress3 ?? null;
        $contractSubItem->operation_type_tonaj3 = $request->operation_type_tonaj3 ?? null;
        $contractSubItem->operation_type_id4 = $request->operation_type_id4 ?? null;
        $contractSubItem->operation_type_fa4 = $operation4['farsi'] ?? null;
        $contractSubItem->operation_type_unit4 = $operation4['unit'] ?? null;
        $contractSubItem->operation_type_amount4 = $request->operation_type_amount4 ?? null;
        $contractSubItem->operation_type_progress4 = $request->operation_type_progress4 ?? null;
        $contractSubItem->operation_type_tonaj4 = $request->operation_type_tonaj4 ?? null;

        $contractSubItem->operator_phone = $request->operator_phone;
        $contractSubItem->operator_name = $request->operator_name;

        $contractSubItem->city_id = $request->city_id;
        $contractSubItem->city_fa = $city_fa->name_fa;
        $contractSubItem->province_id = $request->province_id;
        $contractSubItem->province_fa = $province_fa->name_fa;
        $contractSubItem->axis_type_id = $request->axis_type_id;
        $contractSubItem->axis_name_fa = $request->axis_name_fa;
        $contractSubItem->start_lat = $request->start_lat;
        $contractSubItem->end_lat = $request->end_lat;
        $contractSubItem->start_lng = $request->start_lng;
        $contractSubItem->end_lng = $request->end_lng;
        $contractSubItem->followup_priority_project_id = $request->followup_priority_project_id;
        $contractSubItem->priority_project = $request->priority_project;
        $contractSubItem->progress_project = $progress_project;
        $contractSubItem->last_status_id = $request->last_status_id;
        $contractSubItem->last_digit_project = $request->last_digit_project;
        $contractSubItem->last_function_operator = $request->last_function_operator;
        $contractSubItem->last_payable_operator = $request->last_payable_operator;
        $contractSubItem->complete_payable = $request->complete_payable;
        $contractSubItem->start_way_id = $nominatimService->get_way_id_from_nominatim($request->start_lat, $request->start_lng);
        $contractSubItem->end_way_id  = $nominatimService->get_way_id_from_nominatim($request->end_lat, $request->end_lng);
        $contractSubItem->updated_at_fa = Verta::instance(Verta::now());
        $contractSubItem->user_id = Auth::user()->id;
        $contractSubItem->last_date_update = Carbon::now();

        $contractSubItem->required_bitumen = $request->required_bitumen ?? null;
        $contractSubItem->used_bitumen = $request->used_bitumen ?? null;
        $contractSubItem->bridge_number = $request->bridge_number ?? null;

        $contractSubItem->save();

        $uuid = Str::uuid();
        if ($request->has('image1')) {
            $file1 = $request->file('image1');
            $destinationPath1 = 'storage/contract_subitems/' . now()->year . '/' . now()->month . '/';
            $filename1 = $uuid . '-one.' . $file1->getClientOriginalExtension();
            $file1->move($destinationPath1, $filename1);
            $contractSubItem->update(['image_path1' => $destinationPath1 . $filename1]);
        }

        if ($request->has('image2')) {
            $file2 = $request->file('image2');
            $destinationPath2 = 'storage/contract_subitems/' . now()->year . '/' . now()->month . '/';
            $filename2 = $uuid . '-two.' . $file2->getClientOriginalExtension();
            $file2->move($destinationPath2, $filename2);
            $contractSubItem->update(['image_path2' => $destinationPath2 . $filename2]);
        }

        return response()->json([
            'message' => 'success',
            'data' => $contractSubItem,
        ], 200);
    }

    public function delete(Request $request)
    {
        $csi = ContractSubItems::find($request->id);
        $contract = $csi->Contracts;
        if (! $csi) {
            return response()->json([
                'message' => '404 Not Found'
            ], 404);
        }

        ContractSubItemsHistory::where('subitem_id', $request->id)->delete();
        $csi->delete();
        if (count($contract->subitems) <= 0) {
            $contract->status_rel = 1;
            $contract->save();
        }
        return response()->json([
            'message' => 'success'
        ], 200);
    }

    public function showHistory(Request $request, $id)
    {
        $history = ContractSubItemsHistory::where('subitem_id', $id)->get();

        $data = [];

        foreach ($history as $key => $value) {
            $data[] = array(
                    'axis_name_fa' => $value->axis_name_fa,
                    'axis_type_fa' => $value->axis_type_fa,
                    'axis_type_id' => $value->axis_type_id,
                    'city_fa' => $value->city_fa,
                    'city_id' => $value->city_id,
                    'complete_payable' => $value->complete_payable,
                    'contract_date_from_parent_contract' => $value->contract_date_from_parent_contract,
                    'contract_id' => $value->contract_id,
                    'contract_moshaver_nezarat' => $value->contract_moshaver_nezarat,
                    'contract_moshaver_tarahi' => $value->contract_moshaver_tarahi,
                    'created_at' => $value->created_at,
                    'created_at_fa' => $value->created_at_fa,
                    'end_lat' => $value->end_lat,
                    'end_lng' => $value->end_lng,
                    'end_way_id' => $value->end_way_id,
                    'followup_priority_project' => $value->followup_priority_project,
                    'followup_priority_project_id' => $value->followup_priority_project_id,
                    'id' => $value->id,
                    'image_path1' => $value->image_path1,
                    'image_path2' => $value->image_path2,
                    'last_date_update' => $value->last_date_update,
                    'last_digit_project' => $value->last_digit_project,
                    'last_function_operator' => $value->last_function_operator,
                    'last_payable_operator' => $value->last_payable_operator,
                    'last_status_fa' => $value->last_status_fa,
                    'last_status_fa_for_chart' => $value->last_status_fa_for_chart,
                    'last_status_id' => $value->last_status_id,
                    'operation_type_amount1' => $value->operation_type_amount1,
                    'operation_type_amount2' => $value->operation_type_amount2,
                    'operation_type_amount3' => $value->operation_type_amount3,
                    'operation_type_amount4' => $value->operation_type_amount4,
                    'operation_type_fa1' => $value->operation_type_fa1,
                    'operation_type_fa2' => $value->operation_type_fa2,
                    'operation_type_fa3' => $value->operation_type_fa3,
                    'operation_type_fa4' => $value->operation_type_fa4,
                    'operation_type_id1' => $value->operation_type_id1,
                    'operation_type_id2' => $value->operation_type_id2,
                    'operation_type_id3' => $value->operation_type_id3,
                    'operation_type_id4' => $value->operation_type_id4,
                    'operation_type_progress1' => $value->operation_type_progress1,
                    'operation_type_progress2' => $value->operation_type_progress2,
                    'operation_type_progress3' => $value->operation_type_progress3,
                    'operation_type_progress4' => $value->operation_type_progress4,
                    'operation_type_tonaj1' => $value->operation_type_tonaj1,
                    'operation_type_tonaj2' => $value->operation_type_tonaj2,
                    'operation_type_tonaj3' => $value->operation_type_tonaj3,
                    'operation_type_tonaj4' => $value->operation_type_tonaj4,
                    'operation_type_unit1' => $value->operation_type_unit1,
                    'operation_type_unit2' => $value->operation_type_unit2,
                    'operation_type_unit3' => $value->operation_type_unit3,
                    'operation_type_unit4' => $value->operation_type_unit4,
                    'contract_number' => $value->contract_number,
                    'operator_name' => $value->operator_name,
                    'operator_phone' => $value->operator_phone,
                    'priority_project' => $value->priority_project,
                    'priority_project_fa' => $value->priority_project_fa,
                    'progress_project' => $value->progress_project,
                    'project_title' => $value->project_title,
                    'project_type_fa' => $value->project_type_fa,
                    'project_type_fa_for_chart' => $value->project_type_fa_for_chart,
                    'project_type_id' => $value->project_type_id,
                    'province_fa' => $value->province_fa,
                    'province_id' => $value->province_id,
                    'start_lat' => $value->start_lat,
                    'start_lng' => $value->start_lng,
                    'start_way_id' => $value->start_way_id,
                    'unique_code' => $value->unique_code,
                    'required_bitumen' => $value->required_bitumen,
                    'used_bitumen' => $value->used_bitumen,
                    'bridge_number' => $value->bridge_number,
                    'updated_at' => $value->updated_at,
                    'updated_at_fa' => $value->updated_at_fa,
                    'user_id' => $value->user_id,
                );
        }
        return response()->json([
            'message' => 'success',
            'data' => $data
        ]);
    }

    public function sms_sender($mobile, $msg)
    {
        $client=new SoapClient("http://sms1000.ir/webservice/smspro.asmx?WSDL");
        $result=$client->doSendSMS(
            array(
                'uUsername' => 'rmto',
                'uPassword' => 'Rahdari8
                ',
                'uNumber' => '1000141',
                'uCellphones' => $mobile,
                'uMessage' => $msg,
                'uFarsi' => true,
                'uTopic' => false,
                'uFlash' => false
            )
        );
        $x = $result->doSendSMSResult;
        return $x;
    }

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

    public function getAllOperationList()
    {
        return $response = [
            '1' => [
                'id' => 1,
                'farsi' => 'روکش آسفالت(نگهداری رویه راه)',
                'en_name' => 'maintanance',
                'chart' => 'روکش آسفالت',
                'is_line' => 0,
                'color' => "#ff0000ff",

            ],
            '2' => [
                'id' => 2,
                'farsi' => 'رفع نقاط حادثه خیز',
                'en_name' => 'dangerpoint',
                'chart' => 'نقاط حادثه خیز',
                'is_line' => 0,
                'color' => "#ff0dff",
            ],
            '3' => [
                'id' => 3,
                'farsi' => 'ارتقای ایمنی راه',
                'en_name' => 'upgradesaifty',
                'chart' => 'ایمنی راه',
                'is_line' => 0,
                'color' => "#5900ff",

            ],
            '4' => [
                'id' => 4,
                'farsi' => 'ابنیه فنی(تعمیر و بازسازی)',
                'en_name' => 'technical',
                'chart' => 'ابنیه فنی',
                'is_line' => 0,
                'color' => "#0099ff",
            ],
            '5' => [
                'id' => 5,
                'farsi' => 'راهدارخانه ها',
                'en_name' => 'tollhouse',
                'chart' => 'راهدارخانه',
                'is_line' => 0,
                'color' => "#0c4e17",

            ],
            '6' => [
                'id' => 6,
                'farsi' => 'ساخت راه روستایی',
                'en_name' => 'village',
                'chart' => 'راه روستایی',
                'is_line' => 1,
                'color' => "#bfa30a",

            ],
        ];
    }

    public function getOperationType(Request $request, $id)
    {
        switch ($id) {
            case "1":
                $response = [
                    '101' => [
                        'farsi' => 'روکش آسفالت گرم',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '102' => [
                        'farsi' => 'ماسه آسفالت',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '103' => [
                        'farsi' => 'بازیافت سرد و گرم',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '104' => [
                        'farsi' => 'میکروسرفیسینگ',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '105' => [
                        'farsi' => 'چیپ سیل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '106' => [
                        'farsi' => 'اسلاری سیل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '107' => [
                        'farsi' => 'اسکراب سیل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '108' => [
                        'farsi' => 'فوگ سیل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '109' => [
                        'farsi' => 'سیل کت',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '110' => [
                        'farsi' => 'کیپ سیل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '111' => [
                        'farsi' => 'آسفالت سرد/ردمیکس',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '112' => [
                        'farsi' => 'لکه گیری',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '113' => [
                        'farsi' => 'درزگیری',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                ];
                break;
            case "2":
                $response = [
                    "201" => [
                        'farsi' => 'تعریض راه',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "202" => [
                        'farsi' => 'اصلاح قوس',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "203" => [
                        'farsi' => 'ترانشه برداری',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "204" => [
                        'farsi' => 'اصلاح یا احداث میدان',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "205" => [
                        'farsi' => 'احداث تقاطع غیرهمسطح یا همسطح',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "206" => [
                        'farsi' => 'ایمن سازی با علائم و حفاظ',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "207" => [
                        'farsi' => 'اصلاح ورودی و خروجی',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "208" => [
                        'farsi' => 'احداث تونل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "209" => [
                        'farsi' => 'احداث واربانت',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "210" => [
                        'farsi' => 'تعریض ابنیه فنی',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "211" => [
                        'farsi' => 'ساخت دیوار حایل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    "212" => [
                        'farsi' => 'سایر اقدامات',
                        'unit' => '',
                        'amountable' => 0
                    ]
                ];
                break;
            case "3":
                $response = [
                    '301' => [
                        'farsi' => 'نصب حفاظ بتنی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '302' => [
                        'farsi' => 'نصب حفاظ فلزی/گاردریل',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '303' => [
                        'farsi' => 'اجرای روشنایی طولی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '304' => [
                        'farsi' => 'اجرای روشنایی نقطه ای',
                        'unit' => 'تعداد',
                        'amountable' => 1
                    ],
                    '305' => [
                        'farsi' => 'نصب علائم ایمنی',
                        'unit' => 'تعداد',
                        'amountable' => 1
                    ],
                    '306' => [
                        'farsi' => 'خط کشی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '307' => [
                        'farsi' => 'اصلاح شیب شیروانی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '308' => [
                        'farsi' => 'سایر اقدامات',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '309' => [
                        'farsi' => 'اجرای شیار لرزاننده طولی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '310' => [
                        'farsi' => 'اجرای شیار لرزاننده عرضی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ]
                ];
                break;
            case "4":
                $response = [
                    '401' => [
                        'farsi' => 'تعریض پل/آبرو',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '402' => [
                        'farsi' => 'تعمیرات اساسی پل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '403' => [
                        'farsi' => 'تعمیرات تونل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '404' => [
                        'farsi' => 'تعمیر یا احداث دیوار حائل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '405' => [
                        'farsi' => 'احداث پل جدید',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '406' => [
                        'farsi' => 'احداث کنارگذر پل/تونل',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '407' => [
                        'farsi' => 'سایر اقدامات',
                        'unit' => '',
                        'amountable' => 0
                    ]
                ];
                break;
            case "5":
                $response = [
                    '501' => [
                        'farsi' => 'احداث راهدارخانه جدید',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '502' => [
                        'farsi' => 'احداث انبار شن و نمک',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '503' => [
                        'farsi' => 'نوسازی و بهسازی راهدارخانه',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '504' => [
                        'farsi' => 'احداث آشیانه ماشین آلات',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '505' => [
                        'farsi' => 'محوطه سازی / دیوار کشی',
                        'unit' => '',
                        'amountable' => 0
                    ],
                    '506' => [
                        'farsi' => 'سایر اقدامات',
                        'unit' => '',
                        'amountable' => 0
                    ]
                ];
                break;
            case "6":
                $response = [
                    '601' => [
                        'farsi' => 'عملیات خاکی و زیرسازی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '602' => [
                        'farsi' => 'روسازی',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ],
                    '603' => [
                        'farsi' => 'ابنیه فنی',
                        'unit' => 'دستگاه',
                        'amountable' => 1
                    ],
                    '604' => [
                        'farsi' => 'آسفالت',
                        'unit' => 'کیلومتر',
                        'amountable' => 1
                    ]
                ];
                break;
        }
        return $response;
    }
}
