<?php

namespace App\Http\Controllers;

use App\Helpers\CheckLenght;
use App\Jobs\DeviceJob;
use App\Jobs\DeviceUpdateJob;
use App\Models\DeviceModel;
use App\Models\DeviceReportModel;
use App\Models\DeviceResultModel;
use App\Models\MessageModel;
use App\Models\SettingSiagaModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Helpers\RemoveKarakter;
use App\Models\BantaranSungaiModel;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\Facades\DataTables;

class DeviceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Device',
            'result'    =>  DeviceModel::OrderBy('no', 'desc')->get()
        ];

        return view('/content/device/index', ['pageConfigs' => $pageConfigs], $data);
    }

    public function ambil(Request $request)
    {
        if($request->ajax()) {

            $result = DeviceModel::OrderBy('no', 'desc');
            // ->get();
    
            $DataTables = DataTables::of($result)
                ->addIndexColumn()
                ->addColumn('kode', function ($kode) {
                    if ($kode) {
                        $hasil_kode = $kode->uuid;
                    } else {
                        $hasil_kode = '-';
                    }

                    return $hasil_kode;
                })
                ->addColumn('nama_device', function ($nama_device) {
                    if ($nama_device) {
                        $hasil_device_nama = $nama_device->nama_device;
                    } else {
                        $hasil_device_nama = '-';
                    }

                    return $hasil_device_nama;
                })
                ->addColumn('imei', function ($imei) {
                    if ($imei) {
                        $hasil_imei = $imei->imei;
                    } else {
                        $hasil_imei = '-';
                    }

                    return $hasil_imei;
                })
                ->addColumn('imei', function ($imei) {
                    if ($imei) {
                        $hasil_imei = $imei->imei;
                    } else {
                        $hasil_imei = '-';
                    }

                    return $hasil_imei;
                })
                ->addColumn('koordinat', function ($koordinat) {
                    if ($koordinat) {
                        return "<a href='https://www.google.co.uk/maps?q=" . $koordinat->lat . "," . $koordinat->lng . "' class='btn btn-sm btn-outline-success' target='_blank'><i class='fas fa-map'></i></a>";
                    } else {
                        return "<a href='#' class='btn btn-sm btn-outline-danger'><i class='fas fa-map'></i></a>";
                    }
                })
                ->addColumn('depth', function ($depth) {
                    if ($depth) {
                        return "<span class='badge badge-pill badge-success bg-success'>$depth->depth CM</span>";
                    } else {
                        return "-";
                    }
                })
                ->addColumn('photo_device', function ($photo_device) {
                    if ($photo_device) {
                        $photo = asset("upload/" . $photo_device->photo_device);
                        $img = "
                    <div style='width: 100px !important;height: 80px !important'>
                            <img src='$photo'  style='width: 100% !important;height: 100% !important;object-fit:cover' class='img-thumbnail'>
                          </div>
                    ";
                        return $img;
                    } else {
                        return "-";
                    }
                })
                ->addColumn('status', function ($status) {
                    if ($status->status_run == "1") {
                        return "<span class='badge badge-pill bg-success'>Aktif</span>";
                    } elseif ($status->status_run == "0") {
                        return "<span class='badge badge-pill bg-danger'>Tidak Aktif</span>";
                    } else {
                        return "-";
                    }
                })
                ->addColumn('action', function ($action) {
                    $edit = url("device/show_device/" . $action->no);
                    $hapus = $action->no;
                    $url_hapus = url("device/hapus_device");
                    $token = csrf_field();
                    $method = method_field("DELETE");
                    $aksi = "
                <div class='dropdown'>
                              <button type='button' class='btn dropdown-toggle hide-arrow' data-bs-toggle='dropdown'>
                                
                                <i class='fas fa-ellipsis-vertical'></i>
                              </button>
                              <div class='dropdown-menu dropdown-menu-end'>
                              <a class='dropdown-item' href=' $edit' >
                                <i  class='fas fa-pen me-50'></i>
                                <span>Edit</span>
                              </a>
                              <a class='dropdown-item' href='#'  data-bs-toggle='modal'
                              data-bs-target='#hapus$hapus'>
                                <i class='fas fa-trash me-50'></i>
                                <span>Delete</span>
                              </a>
                            </div>
                            </div>
    
                            <div class='modal fade' id='hapus$hapus' tabindex='-1' aria-hidden='true'>
                            <div class='modal-dialog  modal-lg' role='document'>
                                <form method='POST' enctype='multipart/form-data' class='modal-content' action='$url_hapus'>
                                $token
                                $method
                                <input type='hidden' name='id' value='$hapus'>
                                <div class='modal-header'>
                                    <h5 class='modal-title' id='modalFullTitle'>Hapus Device</h5>
                                    <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
                                </div>
                                <div class='modal-body'>
                                    <div class='p-2 text-center'>
                                    <h4>Apakah Anda Yakin Ingin Menghapus Data Ini!</h4>
                                    </div>
                                </div>
                                <div class='modal-footer'>
                                    <button type='button' class='btn btn-label-secondary' data-bs-dismiss='modal'>Close</button>
                                    <button type='submit' class='btn btn-primary'>Hapus</button>
                                </div>
                                </form>
                            </div>
                            </div>
                ";
                    return $aksi;
                })
                ->rawColumns([
                    'kode',
                    'nama_device',
                    'imei',
                    'koordinat',
                    'depth',
                    'depth_sensor',
                    'photo_device',
                    'status',
                    'action'
                ])
                ->filter(function ($query) use ($request) {
                    // Filtering berdasarkan input dari request
                    if ($request->has('search') && !empty($request->input('search.value'))) {
                        $searchValue = $request->input('search.value');
                        $query->where(function ($innerQuery) use ($searchValue) {
                            // Menambahkan kondisi pencarian ke dalam query
                            // Sesuaikan dengan kolom yang ingin dicari
                            $innerQuery->where('uuid', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('nama_device', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('imei', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('location', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('depth', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('status_run', 'LIKE', '%' . $searchValue . '%');
                        });
                    }
                })
                ->toJson();
                // ->make(true);
            return $DataTables;
        } else {
            return abort(404);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Device'
        ];

        return view('/content/device/created', ['pageConfigs' => $pageConfigs], $data);
    }

    public function show_device(Request $request, $id)
    {
        $nomor = RemoveKarakter::remove_method_get($id);
        $result = DeviceModel::where("no", $id)->count();
        if (!$result || !isset($nomor)) {
            return redirect()->to("device/index/");
        }

        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Device',
            'id'    =>  $id,
            'first' =>  DeviceModel::where("no", $id)->first()
        ];

        return view('/content/device/edit', ['pageConfigs' => $pageConfigs], $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'uuid'  =>  'required|unique:device|alpha_num_dot_comma_space|integer',
            'nama_device'   =>  'required|max:100|unique:device|alpha_num_dot_comma_space|string',
            'imei'  =>  'required|unique:device|alpha_num_dot_comma_space',
            'lat'   =>  'required|max:100|unique:device|regex:/^[0-9,.\\-]+$/',
            'lng'   =>  'required|max:100|unique:device|regex:/^[0-9,.\\-]+$/',
            'location'  =>  'required|max:255',
            'depth' =>  'required|alpha_num_dot_comma_space|integer',
            'file'  =>  'required|max:3024|mimes:jpg,jpeg,png',
            'status'    =>  'integer|alpha_num_dot_comma_space|max:2'
        ],[
            'uuid.required' =>  'Kode Harus Di Isi',
            'uuid.unique'   =>  'Kode Sudah Ada',
            'uuid.alpha_num_dot_comma_space'    =>  'Kode Tidak Valid',
            'uuid.integer'  =>  'Kode Harus Integer',

            'nama_device.required'  =>  'Nama Perangkat Harus Di Isi',
            'nama_device.max'   =>  'Karakter Nama Perangkat Terlalu Panjang',
            'nama_device.string'    =>  'Nama Perangkat Haurs String',
            'nama_device.alpha_num_dot_comma_space' =>  'Nama Perangkat Tidak Valid',

            'imei.required'  =>  'Imei Harus Di Isi',
            'imei.unique'   =>  'Imei Sudah Ada',
            'imei.alpha_num_dot_comma_space'    =>  'Imei Tidak Valid',

            'lat.required'  =>  'Latitude Harus Di Isi',
            'lat.max'   =>  'Karakter Latitude Terlalu Panjang',
            'lat.unique'    =>  'Latitude Sudah Ada',
            'lat.regex' =>  'Karakter Latitude Tidak Valid',
            
            'lng.required'  =>  'Longitude Harus Di Isi',
            'lng.max'   =>  'Karakter Longitude Terlalu Pangjang',
            'lng.unique'    =>  'Longitude Sudah Ada',
            'lng.regex' =>  'Longitude Tidak Valid',
            
            'location.required' =>  'Lokasi Harus Di Isi',
            'location.max'  =>  'Karakter Lokasi Terlalu Panjang',

            'depth.required'    =>  'Kedalaman Sungai Harus Di Isi',
            'depth.alpha_num_dot_comma_space'   =>  'Kedalaman Sungai Tidak Valid',
            'depth.integer' =>  'Kedalaman Sungai Harus Angka',

            'file.required' =>  'File Harus Di Isi',
            'file.max'  =>  'Upload File Maksimal 3 MB',
            'file.mimes'    =>  'Upload File Yang Di Perbolehkan JPG,JPEG,PNG',

            'status.integer'    =>'Status Harus Angka',
            'status.alpha_num_dot_comma_space'  =>  'Status Tidak Valid',
            'status.max'    =>  'Status Terlalu Panjang'
        ]);
        
        
        $nama_device = RemoveKarakter::hapus_karakter($request->nama_device);
        $imei = RemoveKarakter::hapus_karakter($request->imei);
        $lat = RemoveKarakter::hapus_karakter($request->lat);
        $lng = RemoveKarakter::hapus_karakter($request->lng);
        $location = RemoveKarakter::hapus_karakter($request->location);
        $kode = RemoveKarakter::hapus_karakter($request->uuid);
        $kedalaman = RemoveKarakter::hapus_karakter($request->depth);

        $uuid = CheckLenght::lenght($request->uuid);
        $leng_lat = CheckLenght::lenght($request->lat);
        $leng_lng = CheckLenght::lenght($request->lng);
        $depth = CheckLenght::lenght($request->depth);
        if($uuid > 255) {
            return redirect()->back()->with('error',"Karakter kode terlalu panjang");
        }
        
        if($leng_lat > 100) {
            return redirect()->back()->with('error',"Karakter Latitude terlalu panjang");
        }
        
        if($leng_lng > 100) {
            return redirect()->back()->with('error',"Karakter Longitude terlalu panjang");
        }
        
        if($depth > 11) {
            return redirect()->back()->with('error',"Karakter depth terlalu panjang");
        }

        try {
            $status = RemoveKarakter::remove_method_get($request->status);
            if ($status) {
                if ($status == 1) {
                    $active = "1";
                } else {
                    $active = "0";
                }
            } else {
                $active = "0";
            }
            $file = $request->file('file');
            $tujuan_upload = 'upload';
            $nama_file = $file->getClientOriginalName();
            $check_file = CheckLenght::lenght($nama_file);
            if($check_file > 255) {
                return redirect()->back()->with('error','Karakter Nama File terlalu panjang');
            }
            $file->move($tujuan_upload, $file->getClientOriginalName());

            $device = new DeviceModel();
            $device->uuid = $kode;
            $device->nama_device = $nama_device;
            $device->imei = $imei;
            $device->lat = $lat;
            $device->lng = $lng;
            $device->location = $location;
            $device->depth = $kedalaman;
            $device->photo_device = $nama_file;
            $device->status_run = $active;
            $device->save();
            // $job = new DeviceJob($request->uuid,$request->nama_device,$request->imei,$request->lat,$request->lng,$request->location,$request->depth,$request->depth_sensor,$nama_file,$active);
            // $this->dispatch($job);

            return redirect()->to("device/index")->with("success", "Data Berhasil Ditambahkan");
        } catch (\Throwable $th) {
            return redirect()->back()->with("error", "Data Gagal Ditambahkan");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Device'
        ];

        return view('/content/device/edit', ['pageConfigs' => $pageConfigs], $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $request->validate([
            'nama_device'   =>  'required|max:100|alpha_num_dot_comma_space|string',
            'imei'  =>  'required|alpha_num_dot_comma_space',
            'lat'   =>  'required|max:100|regex:/^[0-9,.\\-]+$/',
            'lng'   =>  'required|max:100|regex:/^[0-9,.\\-]+$/',
            'location'  =>  'required|max:255',
            'depth' =>  'required|alpha_num_dot_comma_space|integer',
            'file'  =>  'max:3024|mimes:jpg,jpeg,png',
            'status'    =>  'integer|alpha_num_dot_comma_space|max:2'
        ],
        [
            'nama_device.required'  =>  'Nama Perangkat Harus Di Isi',
            'nama_device.max'   =>  'Karakter Nama Perangkat Terlalu Panjang',
            'nama_device.string'    =>  'Nama Perangkat Haurs String',
            'nama_device.alpha_num_dot_comma_space' =>  'Nama Perangkat Tidak Valid',

            'imei.required'  =>  'Imei Harus Di Isi',
            'imei.unique'   =>  'Imei Sudah Ada',
            'imei.alpha_num_dot_comma_space'    =>  'Imei Tidak Valid',

            'lat.required'  =>  'Latitude Harus Di Isi',
            'lat.max'   =>  'Karakter Latitude Terlalu Panjang',
            'lat.unique'    =>  'Latitude Sudah Ada',
            'lat.regex' =>  'Karakter Latitude Tidak Valid',
            
            'lng.required'  =>  'Longitude Harus Di Isi',
            'lng.max'   =>  'Karakter Longitude Terlalu Pangjang',
            'lng.unique'    =>  'Longitude Sudah Ada',
            'lng.regex' =>  'Longitude Tidak Valid',
            
            'location.required' =>  'Lokasi Harus Di Isi',
            'location.max'  =>  'Karakter Lokasi Terlalu Panjang',

            'depth.required'    =>  'Kedalaman Sungai Harus Di Isi',
            'depth.alpha_num_dot_comma_space'   =>  'Kedalaman Sungai Tidak Valid',
            'depth.integer' =>  'Kedalaman Sungai Harus Angka',

            'file.required' =>  'File Harus Di Isi',
            'file.max'  =>  'Upload File Maksimal 3 MB',
            'file.mimes'    =>  'Upload File Yang Di Perbolehkan JPG,JPEG,PNG',

            'status.integer'    =>'Status Harus Angka',
            'status.alpha_num_dot_comma_space'  =>  'Status Tidak Valid',
            'status.max'    =>  'Status Terlalu Panjang'
        ]);

        $id = RemoveKarakter::remove_method_get($request->id);

        $check_result = DeviceModel::where("no", $id)->count();
        if (!$check_result || !isset($id)) {
            return redirect()->back()->with("error", "Data Gagal Diupdate");
        }

        
        $nama_device = RemoveKarakter::hapus_karakter($request->nama_device);
        $imei = RemoveKarakter::hapus_karakter($request->imei);
        $lat = RemoveKarakter::hapus_karakter($request->lat);
        $lng = RemoveKarakter::hapus_karakter($request->lng);
        $location = RemoveKarakter::hapus_karakter($request->location);
        $kedalaman = RemoveKarakter::hapus_karakter($request->depth);

        $leng_lat = CheckLenght::lenght($request->lat);
        $leng_lng = CheckLenght::lenght($request->lng);
        $depth = CheckLenght::lenght($request->depth);
        
        if($leng_lat > 100) {
            return redirect()->back()->with('error',"Karakter Latitude terlalu panjang");
        }
        
        if($leng_lng > 100) {
            return redirect()->back()->with('error',"Karakter Longitude terlalu panjang");
        }
        
        if($depth > 11) {
            return redirect()->back()->with('error',"Karakter depth terlalu panjang");
        }

        try {
            $status = RemoveKarakter::remove_method_get($request->status);
            if ($status) {
                if ($status == 1) {
                    $active = "1";
                } else {
                    $active = "0";
                }
            } else {
                $active = "0";
            }
            $file = $request->file('file');
            if ($file) {
                $tujuan_upload = 'upload';
                $nama_file = $file->getClientOriginalName();
                $check_file = CheckLenght::lenght($nama_file);
                if($check_file > 255) {
                    return redirect()->back()->with('error','Karakter nama file terlalu panjang');
                }
                $file->move($tujuan_upload, $file->getClientOriginalName());
            } else {
                $nama_file = $request->file_lama;
            }


            DeviceModel::where("no", $id)->update([
                'nama_device'   =>  $nama_device,
                'imei'  =>  $imei,
                'lat'   =>  $lat,
                'lng'   =>  $lng,
                'location'  =>  $location,
                'depth' =>  $kedalaman,
                'photo_device'  =>  $nama_file,
                'status_run'    =>  $active
            ]);
            // $job = new DeviceUpdateJob($request->uuid,$request->nama_device,$request->imei,$request->lat,$request->lng,$request->location,$request->depth,$request->depth_sensor,$nama_file,$active,$id);
            // $this->dispatch($job);
            return redirect()->to("device/index")->with("success", "Data Berhasil Diupdate");
        } catch (\Throwable $th) {
            return redirect()->back()->with("error", "Data Gagal Diupdate");
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $id = RemoveKarakter::remove_method_get($request->id);
        $check_result = DeviceModel::where("no", $id)->count();
        if (!$check_result || !isset($id)) {
            return redirect()->back()->with("error", "Data Gagal Dihapus");
        }
        try {
            $result = SettingSiagaModel::where("uuid_device", $id)->count();
            $pesan = MessageModel::where("uuid_device", $id)->count();
            $report = DeviceReportModel::where("uuid_device", $id)->count();
            $resul = DeviceResultModel::where("uuid_device", $id)->count();
            $bantaran = BantaranSungaiModel::where('perangkat_id',$id)->count();
            if ($result || $pesan || $report || $resul || $bantaran) {
                return redirect()->back()->with('error', "Data ini tidak boleh di hapus karena sudah berelasi");
            }
            DeviceModel::where("no", $id)->delete();
            return redirect()->back()->with("success", "Data Berhasil Dihapus");
        } catch (\Throwable $th) {
            return redirect()->back()->with("error", "Data Gagal Dihapus");
        }
    }
}
