<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CMMS_Form;
use App\Models\CMMS_Forms_histories;
use App\Models\CMMS_Province;
use App\Models\CmmsDemo;
use App\Services\FMSService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Hekmatinasser\Verta\Verta;
use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;


class CMMSController extends Controller
{
    public function getVehicleActivity(Request $request, FMSService $FMSService)
    {
        
        if (!$request->machineCode || !$request->startDT || !$request->endDT || !$request->minStopDuration) {
            return response()->json([
                'message' => 'error'
            ]);
        }

        $server_output = $FMSService->getVehicleActivity($request);
        
        $d = json_decode($server_output, true);
        
        if ($d['ResultCode'] != 0) {
            return response()->json([
                'message' => 'failed',
            ]);
        }
        
        return response()->json([
            'message' => 'success',
            'data' => $d
        ]);

    }

    public function getVehicleLastPoints(Request $request, FMSService $FMSService)
    {
        
        if (!$request->machineCode) {
            return response()->json([
                'message' => 'error'
            ]);
        }

        $server_output = $FMSService->getVehicleLastPoints($request);
        
        $d = json_decode($server_output, true);
        return $d;
        if ($d['ResultCode'] != 0) {
            return response()->json([
                'message' => 'failed',
            ]);
        }
        
        return response()->json([
            'message' => 'success',
            'data' => $d
        ]);

    }

    public function getVehicleActivitySummary(Request $request, FMSService $FMSService)
    {
        
        if (!$request->machineCode || !$request->startDT || !$request->endDT) {
            return response()->json([
                'message' => 'error'
            ]);
        }

        $server_output = $FMSService->getVehicleActivitySummary($request);
        
        $d = json_decode($server_output, true);
        
        if ($d['ResultCode'] != 0) {
            return response()->json([
                'message' => 'failed',
            ]);
        }
        
        return response()->json([
            'message' => 'success',
            'data' => $d
        ]);

    }


    public function getVehicleData(Request $request, FMSService $FMSService)
    {
        $server_output = $FMSService->getVehicleData($request);
        
        $d = json_decode($server_output);
        
        if ($d[0]->ResultCode != 0) {
            return response()->json([
                'message' => 'failed',
            ]);
        }
        
        return response()->json([
            'message' => 'success',
            'data' => $d[0]
        ]);


    }


    public function publicIndex()
    {
        $fms = CMMS_Form::all();
        
        return response()->json([
            'data' => $fms
        ]);
    }

    public function index()
    {
        if (Auth::user()->hasRole('superadmin')) {
            $fms = CMMS_Form::all();
        } else {
            $fms = CMMS_Form::where('user_id', Auth::user()->id)->get();
        }
        
        return response()->json([
            'data' => $fms
        ]);
    }


    public function edit($id)
    {
        $cmms = CMMS_Form::where('id', $id)->first();
        return response()->json([
            'message' => 'success',
            'data' => $cmms
        ]);      
    }



    public function store(Request $request)
    {
        $uuid = Str::uuid();

        foreach (CMMS_Province::where('province_id', $request->only('province_id'))->get() as $prov_item) {
            $province_fa = $prov_item->province_fa;
        }
        foreach (CMMS_Province::where('province_id', $request->only('province_id'))->get() as $item) {
            $area_code = $item->area_code;
        }
        $hasMachine = CMMS_Form::where('car_type', $request->car_type)
            ->where('province_id', $request->province_id)
            ->orderBy('created_at', 'DESC')->first();


        if (strlen($request->province_id) == '1') {
            $province_id = '0' . $request->province_id;
        } else {
            $province_id = $request->province_id;
        }

        if ($hasMachine) {
            $latestItem = CMMS_Form::where('province_id', $request->province_id)
                ->where('car_type', $request->car_type)
                ->orderBy('created_at', 'desc')
                ->first();


            // add counter
            $getThreeLastChar = substr($hasMachine->form_number, -3);
            $temp = intval($getThreeLastChar);
            $temp++;
            if (strlen($temp) == '3') {
                $new = $temp;
            } elseif (strlen($temp) == '2') {
                $new = '0' . $temp;
            } else {
                $new = '00' . $temp;
            }

            $form_number = 'F:H-' . $request->car_type . $area_code . $province_id . $new;
        } else {
            $form_number = 'F:H-' . $request->car_type . $area_code . $province_id . '001';
        }


        $city = \App\Models\City::where('id', $request->city_id)
            ->select('id', 'name_fa')->first();

        $city_fa = $city->name_fa;

        switch ($request->car_type) {
            case "B":
                $car_type_fa = 'بلدوزر';
                break;
            case "L":
                $car_type_fa = 'لودر';
                break;
            case "G":
                $car_type_fa = 'گریدر';
                break;
            case "Ex":
                $car_type_fa = 'بیل مکانیکی';
                break;
        }

        $create_form = CMMS_Form::create([
            'dedicated_number' => $request->dedicated_number,
            'chassis_number' => $request->chassis_number,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'city_id' => $request->city_id,
            'city_fa' => $city_fa,
            'total_points' => $request->total_points,
            'device_name' => $request->device_name,
            'gps_code' => $request->gps_code,
            'operator_phone' => $request->operator_phone,
            'operator_name' => $request->operator_name,
            'operator_nationalcode' => $request->operator_nationalcode,
            'form_number' => $form_number,
            'car_type' => $request->car_type,
            'motor' => $request->motor,
            'motor_description' => $request->motor_description,
            'motor_score' => $request->motor_score,
            'power' => $request->power,
            'power_description' => $request->power_description,
            'power_score' => $request->power_score,
            'zirbandi' => $request->zirbandi,
            'zirbandi_description' => $request->zirbandi_description,
            'zirbandi_score' => $request->zirbandi_score,
            'chassis' => $request->chassis,
            'chassis_description' => $request->chassis_description,
            'chassis_score' => $request->chassis_score,
            'electrical' => $request->electrical,
            'electrical_description' => $request->electrical_description,
            'electrical_score' => $request->electrical_score,
            'safety' => $request->safety,
            'safety_description' => $request->safety_description,
            'safety_score' => $request->safety_score,
            'gps' => $request->gps,
            'gps_description' => $request->gps_description,
            'gps_score' => $request->gps_score,
            'color' => $request->color,
            'color_description' => $request->color_description,
            'color_score' => $request->color_score,
            'bucket' => $request->bucket,
            'bucket_description' => $request->bucket_description,
            'bucket_score' => $request->bucket_score,
            'hydraulic' => $request->hydraulic,
            'hydraulic_description' => $request->hydraulic_description,
            'hydraulic_score' => $request->hydraulic_score,
            'jolobandi' => $request->jolobandi,
            'jolobandi_description' => $request->jolobandi_description,
            'jolobandi_score' => $request->jolobandi_score,
            'ripper' => $request->ripper,
            'ripper_description' => $request->ripper_description,
            'ripper_score' => $request->ripper_score,
            'service_status' => $request->service_status,
            'service_description' => $request->service_description,
            'fuel_form' => $request->fuel_form,
            'fuel_description' => $request->fuel_description,
            'question1' => $request->question1,
            'question2' => $request->question2,
            'question3' => $request->question3,
            'question4' => $request->question4,
            'question5' => $request->question5,
            'auditor_name' => $request->auditor_name,
            'auditor_position' => $request->auditor_position,
            'member1_name' => $request->member1_name,
            'member1_position' => $request->member1_position,
            'member2_name' => $request->member2_name,
            'member2_position' => $request->member2_position,
            'member3_name' => $request->member3_name,
            'member3_position' => $request->member3_position,
            'user_id' => Auth::user()->id,
            'car_type_fa' => $car_type_fa,
            'created_at_fa' => Verta::now(),
            'updated_at_fa' => Verta::now(),
        ]);

        $machineData = CmmsDemo::where('machine_code', $request->dedicated_number)->first();

        CMMS_Forms_histories::create([
            'user_id' => Auth::user()->id,
            'cmms_form_id' => $create_form->id,
            'previous_chassis_number' => $machineData->body_number ?? null,
            'previous_province_id' => null,
            'previous_province_fa' => $machineData->unit_group_fa ?? null,
            'previous_city_id' => null,
            'previous_city_fa' => $machineData->unit_name ?? null,
            'previous_device_name' => $machineData->car_name ?? null,
            'previous_gps_code' => $machineData->gps_code ?? null,
            'previous_operator_name' => $machineData->driver_name ?? null,
            'previous_operator_nationalcode' => null,
            'previous_operator_phone' => $machineData->mobile ?? null,
        ]);

        if ($request->has('image1')) {
            $image1 = $request->file('image1');
            $destinationPath1 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename1 = $uuid . '-imageOne.' . $image1->getClientOriginalExtension();
            $image1->move($destinationPath1, $filename1);
            $create_form->update(['image1' => $destinationPath1 . $filename1]);
        }
        if ($request->has('image2')) {
            $image2 = $request->file('image2');
            $destinationPath2 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename2 = $uuid . '-imageTwo.' . $image2->getClientOriginalExtension();
            $image2->move($destinationPath2, $filename2);
            $create_form->update(['image2' => $destinationPath2 . $filename2]);
        }
        if ($request->has('image3')) {
            $image3 = $request->file('image3');
            $destinationPath3 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename3 = $uuid . '-imageThree.' . $image3->getClientOriginalExtension();
            $image3->move($destinationPath3, $filename3);
            $create_form->update(['image3' => $destinationPath3 . $filename3]);
        }
        if ($request->has('file1')) {
            $file1 = $request->file('file1');
            $destinationPath4 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename4 = $uuid . '-Form.' . $file1->getClientOriginalExtension();
            $file1->move($destinationPath4, $filename4);
            $create_form->update(['file1' => $destinationPath4 . $filename4]);
        }
        $machineData->proccessed = 1;
        $machineData->save();

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


    public function update(Request $request, $id)
    {
        $uuid = Str::uuid();

        foreach (CMMS_Province::where('province_id', $request->only('province_id'))->get() as $prov_item) {
            $province_fa = $prov_item->province_fa;
        }
        foreach (CMMS_Province::where('province_id', $request->only('province_id'))->get() as $item) {
            $area_code = $item->area_code;
        }
        $hasMachine = CMMS_Form::where('car_type', $request->car_type)
            ->where('province_id', $request->province_id)
            ->orderBy('created_at', 'DESC')->first();


        if (strlen($request->province_id) == '1') {
            $province_id = '0' . $request->province_id;
        } else {
            $province_id = $request->province_id;
        }

        if ($hasMachine) {
            $latestItem = CMMS_Form::where('province_id', $request->province_id)
                ->where('car_type', $request->car_type)
                ->orderBy('created_at', 'desc')
                ->first();

            // add counter
            $getThreeLastChar = substr($hasMachine->form_number, -3);
            $temp = intval($getThreeLastChar);
            $temp++;
            if (strlen($temp) == '3') {
                $new = $temp;
            } elseif (strlen($temp) == '2') {
                $new = '0' . $temp;
            } else {
                $new = '00' . $temp;
            }

            $form_number = 'F:H-' . $request->car_type . $area_code . $province_id . $new;
        } else {
            $form_number = 'F:H-' . $request->car_type . $area_code . $province_id . '001';
        }


        $city = \App\Models\City::where('id', $request->city_id)
            ->select('id', 'name_fa')->first();

        $city_fa = $city->name_fa;

        switch ($request->car_type) {
            case "B":
                $car_type_fa = 'بلدوزر';
                break;
            case "L":
                $car_type_fa = 'لودر';
                break;
            case "G":
                $car_type_fa = 'گریدر';
                break;
            case "Ex":
                $car_type_fa = 'بیل مکانیکی';
                break;
        }
        $cmms = CMMS_Form::find($id);
        $cmms->update([
            'dedicated_number' => $request->dedicated_number,
            'chassis_number' => $request->chassis_number,
            'province_id' => $request->province_id,
            'province_fa' => $province_fa,
            'city_id' => $request->city_id,
            'city_fa' => $city_fa,
            'total_points' => $request->total_points,
            'device_name' => $request->device_name,
            'gps_code' => $request->gps_code,
            'operator_phone' => $request->operator_phone,
            'operator_name' => $request->operator_name,
            'operator_nationalcode' => $request->operator_nationalcode,
            'form_number' => $form_number,
            'car_type' => $request->car_type,
            'motor' => $request->motor,
            'motor_description' => $request->motor_description,
            'motor_score' => $request->motor_score,
            'power' => $request->power,
            'power_description' => $request->power_description,
            'power_score' => $request->power_score,
            'zirbandi' => $request->zirbandi,
            'zirbandi_description' => $request->zirbandi_description,
            'zirbandi_score' => $request->zirbandi_score,
            'chassis' => $request->chassis,
            'chassis_description' => $request->chassis_description,
            'chassis_score' => $request->chassis_score,
            'electrical' => $request->electrical,
            'electrical_description' => $request->electrical_description,
            'electrical_score' => $request->electrical_score,
            'safety' => $request->safety,
            'safety_description' => $request->safety_description,
            'safety_score' => $request->safety_score,
            'gps' => $request->gps,
            'gps_description' => $request->gps_description,
            'gps_score' => $request->gps_score,
            'color' => $request->color,
            'color_description' => $request->color_description,
            'color_score' => $request->color_score,
            'bucket' => $request->bucket,
            'bucket_description' => $request->bucket_description,
            'bucket_score' => $request->bucket_score,
            'hydraulic' => $request->hydraulic,
            'hydraulic_description' => $request->hydraulic_description,
            'hydraulic_score' => $request->hydraulic_score,
            'jolobandi' => $request->jolobandi,
            'jolobandi_description' => $request->jolobandi_description,
            'jolobandi_score' => $request->jolobandi_score,
            'ripper' => $request->ripper,
            'ripper_description' => $request->ripper_description,
            'ripper_score' => $request->ripper_score,
            'service_status' => $request->service_status,
            'service_description' => $request->service_description,
            'fuel_form' => $request->fuel_form,
            'fuel_description' => $request->fuel_description,
            'question1' => $request->question1,
            'question2' => $request->question2,
            'question3' => $request->question3,
            'question4' => $request->question4,
            'question5' => $request->question5,
            'auditor_name' => $request->auditor_name,
            'auditor_position' => $request->auditor_position,
            'member1_name' => $request->member1_name,
            'member1_position' => $request->member1_position,
            'member2_name' => $request->member2_name,
            'member2_position' => $request->member2_position,
            'member3_name' => $request->member3_name,
            'member3_position' => $request->member3_position,
            'user_id' => Auth::user()->id,
            'car_type_fa' => $car_type_fa,
            'updated_at_fa' => Verta::now(),
        ]);

        if ($request->has('image1')) {
            $image1 = $request->file('image1');
            $destinationPath1 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename1 = $uuid . '-imageOne.' . $image1->getClientOriginalExtension();
            $image1->move($destinationPath1, $filename1);
            $cmms->update(['image1' => $destinationPath1 . $filename1]);
        }
        if ($request->has('image2')) {
            $image2 = $request->file('image2');
            $destinationPath2 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename2 = $uuid . '-imageTwo.' . $image2->getClientOriginalExtension();
            $image2->move($destinationPath2, $filename2);
            $cmms->update(['image2' => $destinationPath2 . $filename2]);
        }
        if ($request->has('image3')) {
            $image3 = $request->file('image3');
            $destinationPath3 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename3 = $uuid . '-imageThree.' . $image3->getClientOriginalExtension();
            $image3->move($destinationPath3, $filename3);
            $cmms->update(['image3' => $destinationPath3 . $filename3]);
        }
        if ($request->has('file1')) {
            $file1 = $request->file('file1');
            $destinationPath4 = 'storage/cmms/' . now()->year . '/' . now()->month . '/';
            $filename4 = $uuid . '-Form.' . $file1->getClientOriginalExtension();
            $file1->move($destinationPath4, $filename4);
            $cmms->update(['file1' => $destinationPath4 . $filename4]);
        }

        $history = CMMS_Forms_histories::create([
            'user_id' => Auth::user()->id,
            'cmms_form_id' => $id,
            'previous_chassis_number' => $cmms->chassis_number,
            'previous_province_id' => $cmms->province_id,
            'previous_province_fa' => $cmms->province_name,
            'previous_city_id' => $cmms->city_id,
            'previous_city_fa' => $cmms->city_name,
            'previous_device_name' => $cmms->device_name,
            'previous_gps_code' => $cmms->gps_code,
            'previous_operator_name' => $cmms->operator_name,
            'previous_operator_nationalcode' => $cmms->operator_nationalcode,
            'previous_operator_phone' => $cmms->operator_phone,
            'previous_image1' => $cmms->image1 ?? null,
            'previous_image2' => $cmms->image2 ?? null,
            'previous_image3' => $cmms->image3 ?? null,
            'previous_file1' => $cmms->file1 ?? null,
            'previous_form_number' => $cmms->form_number
        ]);

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



    public function getProvinces()
    {
        $provinces = CMMS_Province::all();

        return response()->json([
           'data' => $provinces
        ]);
    }
    
    public function getByMachineCode(Request $request)
    {
        $machineData = CmmsDemo::where('machine_code', $request->dedicated_number)->first();

        return response()->json([
            'status' => 'success',
           'data' => $machineData
        ]);
    }
    public function search(Request $request)
    {
        $request->validate([
            'data' => 'required'
        ]);
        $sql = "SELECT machine_code FROM cmms_demos
        WHERE LOCATE('".$request->data."', cmms_demos.machine_code) > 0 and proccessed = 0
        limit 5";
        $data = DB::select($sql);
        $arr = [];
        foreach ($data as $value) {
            $arr[] = $value->machine_code;
        }
        return response()->json([
            'status'       => 'succeed',
            'message'      => 'yes',
            'status_bool'  => 1,
            'data'       => $arr,
        ], 200);
    }
    public function get_cities(Request $request){
        $request->validate([
            'id' => 'required|integer|exists:cmms_province,id'
        ]);
        $p_id = CMMS_Province::where('province_id', $request->id)->first();
        $p_id = $p_id->rms_code;
        $cities = \App\Models\City::where('province_id', $p_id)->select('id', 'name_fa')->get();
        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $cities
        ], 200);
    }

}