<?php

namespace App\Http\Controllers;

use App\Exports\LaporanKetinggianAirExport;
use App\Helpers\RemoveKarakter;
use App\Models\DeviceModel;
use App\Models\DeviceReportModel;
use App\Models\SettingSiagaModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Pagination\LengthAwarePaginator;

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



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

    public function ambil_search(Request $request, $no_device, $awal, $akhir)
    {
        if ($request->ajax()) {
            $device = RemoveKarakter::remove_method_get($no_device);

            if (!isset($device) || !isset($awal) || !isset($akhir)) {
                return abort(404);
            }
            $result = DeviceReportModel::select(
                'device_reports.uuid',
                'device_reports.uuid_device',
                'device_reports.depth',
                'device_reports.date_report',
                'device_reports.time_report',
                'device.no',
                'device.nama_device',
                'device.location',
                'device.lat',
                'device.lng'
            )
                ->join('device', 'device_reports.uuid_device', '=', 'device.no')
                ->where('device_reports.uuid_device', $device)
                ->whereBetween('date_report', [$awal, $akhir]);
                // ->get();
            $DataTables = DataTables::of($result)
                ->addIndexColumn()
                ->addColumn('depth', function ($depth) {
                    if($depth) {
                        $rt = '<span class="badge badge-pill bg-success">' . $depth->depth . ' CM</span>';
                    } else {
                        $rt = '-';
                    }
                    return $rt;
                })
                ->addColumn('date_report', function ($date_report) {
                    if($date_report) {
                        $dater = date("d, F Y", strtotime($date_report->date_report));
                    } else {
                        $dater = '-';
                    }
                    return $dater;
                })
                ->addColumn("time_report", function ($time_report) {
                    if($time_report) {
                        $lima = date("H:i", strtotime($time_report->time_report));
                    } else {
                        $lima = '-';
                    }
                    return $lima;
                })
                ->addColumn('lat', function ($lat) {
                    if ($lat) {
                        $urlt = "https://www.google.co.uk/maps?q=" . $lat->lat . ',' . $lat->lng;
                        $map = "<a href='$urlt' class='btn btn-sm btn-outline-success' target='_blank'><i class='fas fa-map'></i></a>";
                        return $map;
                    } else {
                        return "-";
                    }
                })
                ->rawColumns(['depth', 'lat'])
                ->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('device_reports.depth', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device_reports.date_report', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device_reports.time_report', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device.nama_device', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device.location', 'LIKE', '%' . $searchValue . '%');
                        });
                    }
                })
                ->toJson();
                // ->make(true);
            return $DataTables;
        } else {
            return abort(404);
        }
    }

    public function ambil(Request $request)
    {

        if($request->ajax()) {
            
            $result = DeviceReportModel::select('device_reports.uuid',
            'device_reports.depth',
            'device_reports.date_report',
            'device_reports.time_report',
            'device.no',
            'device.nama_device',
            'device.location')
        ->join('device', 'device_reports.uuid_device', '=', 'device.no')
        ->orderBy('device_reports.uuid', 'DESC');
            $DataTables = DataTables::of($result)
                ->addIndexColumn()
                ->addColumn('nama_device', function ($nama_device) {
                    if($nama_device) {
                        $nama_device_alat = $nama_device->nama_device;
                    } else {
                        $nama_device_alat = '-';
                    }
                    return $nama_device_alat;
                })
                ->addColumn('location', function ($location) {
                    if($location) {
                        $location_alat = $location->location;
                    } else {
                        $location_alat = '-';
                    }
                    return $location_alat;
                })
                ->addColumn('depth', function ($depth) {
                    if($depth) {
                        $rt = '<span class="badge badge-pill bg-success">' . $depth->depth . ' CM</span>';
                    } else {
                        $rt = '-';
                    }
                    return $rt;
                })
                ->addColumn('date_report', function ($date_report) {
                    if($date_report) {
                        $simpan  = date("d, F Y", strtotime($date_report->date_report));
                    } else {
                        $simpan = '-';
                    }
                    return $simpan;
                })
                ->addColumn("time_report", function ($time_report) {
                    if($time_report) {
                        $kemana = date("H:i", strtotime($time_report->time_report));
                    } else {
                        $kemana = '-';
                    }
                    return $kemana;
                })
                ->rawColumns([
                    'nama_device',
                    'location',
                    'depth',
                    'date_report',
                    'time_report'
                ])
                ->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('device_reports.depth', 'LIKE', '%' . $searchValue . '%')
                                ->orWhere('device_reports.date_report', 'LIKE', '%' . $searchValue . '%')
                                ->orWhere('device_reports.time_report', 'LIKE', '%' . $searchValue . '%')
                                ->orWhere('device.nama_device', 'LIKE', '%' . $searchValue . '%')
                                ->orWhere('device.location', 'LIKE', '%' . $searchValue . '%');
                        });
                    }
                })
                ->toJson();
            return $DataTables;
        } else {
            return abort(404);
        }
    }

    public function ambil_laporan_ketinggian(Request $request)
    {
        if($request->ajax()) {
     
            $result = DeviceReportModel::select('device_reports.uuid',
            'device_reports.depth',
            'device_reports.date_report',
            'device_reports.time_report',
            'device.no',
            'device.nama_device',
            'device.location',
            'device.lat',
            'device.lng')
        ->join('device', 'device_reports.uuid_device', '=', 'device.no')
        ->orderBy('device_reports.uuid', 'DESC');
        // ->get();
        
            $DataTables = DataTables::of($result) 
                ->addIndexColumn()
                ->addColumn('depth', function ($depth) {
                    if($depth) {
                        $rt = '<span class="badge badge-pill bg-success">' . $depth->depth . ' CM</span>';
                    } else {
                        $rt = '-';
                    }
                    return $rt;
                })
                ->addColumn('date_report', function ($date_report) {
                    if($date_report) {
                        $tu =date("d, F Y", strtotime($date_report->date_report)); 
                    } else {
                        $tu = '-';
                    }
                    return $tu;
                })
                ->addColumn("time_report", function ($time_report) {
                    if($time_report) {
                        $satu = date("H:i", strtotime($time_report->time_report));
                    } else {
                        $satu = '-';
                    }
                    return $satu;
                })
                ->addColumn('lat', function ($koordinat) {
                    if($koordinat) {
                        $urlt = "https://www.google.co.uk/maps?q=" . $koordinat->lat . ',' . $koordinat->lng;
                        $map = "<a href='$urlt' class='btn btn-sm btn-outline-success' target='_blank'><i class='fas fa-map'></i></a>";
                    }   else {
                        $map = '-';
                    }
                    return $map;
                })
                ->rawColumns([
                    'depth',
                    'lat'
                ])
                
                ->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('device_reports.depth', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device_reports.date_report', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device_reports.time_report', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device.nama_device', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('device.location', '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 laporan_ketinggian_air()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Laporan Ketinggian Air',
            'result'    =>  DeviceReportModel::OrderBy('uuid', 'desc')->get(),
            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
        ];

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function seacrh(Request $request)
    {
        $request->validate([
            'awal'  =>  'required|date',
            'akhir' =>  'required|date',
            'device'    =>  'required|integer|alpha_num|max:255'
        ], [
            'awal.required' =>  'Tanggal Mulai Harus Di Isi',
            'awal.date' =>  'Tanggal Mulai Harus Bertype Tanggal',

            'akhir.required' =>  'Tanggal Sampai Harus Di Isi',
            'akhir.date' =>  'Tanggal Sampai Harus Bertype Tanggal',

            'device.required'   =>  'Pilih Perangkat Harus Di Isi',
            'device.integer'    =>  'Pilih Perangkat Harus Integer',
            'device.max'    =>  'Karakter Pilih Perangkat Terlalu Panjang',
            'device.alpha_num'  =>  'Pilih Perangkat Tidak Valid'
        ]);

        $awal  = date("Y-m-d", strtotime($request->awal));
        $akhir = date("Y-m-d", strtotime($request->akhir));
        if ($akhir <= $awal) {
            return redirect()->to("laporan_ketinggian_air/index")->with("error", "Tanggal Sampai Tidak Boleh Kurang Atau Sama Dengan Tanggal Mulai");
        }

        try {
            $kirim = RemoveKarakter::hapus_karakter($request->kirim);
            $device = RemoveKarakter::remove_method_get($request->device);
            if (isset($kirim)) {
                // filter
                if ($kirim == "filter") {
                    // pilih device
                    $count_device = DeviceReportModel::where("uuid_device", $device)->whereBetween('date_report', [$awal, $akhir])->where("status", "aktif")->count();
                    if ($count_device) {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'alat'  =>  $device,
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                        ];

                        return view('/content/ketinggian_air/search', ['pageConfigs' => $pageConfigs], $data);
                    } else {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'alat'  =>  $device,
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                        ];
                        session()->flash('error', 'Data Tidak Ditemukan');
                        return view('/content/ketinggian_air/search', ['pageConfigs' => $pageConfigs], $data);
                    }
                } elseif ($kirim == "excel") {
                    $count_device = DeviceReportModel::where("uuid_device", $device)->whereBetween('date_report', [$awal, $akhir])->where("status", "aktif")->count();
                    if ($count_device) {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $nama_device = DeviceModel::where("no", $device)->first();
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'nama_device'   => $nama_device,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                        ];
                        return Excel::download(new LaporanKetinggianAirExport($awal, $akhir, $device, $nama_device), 'laporan_ketinggian_air_' . $awal . '_' . $akhir . '.xlsx');
                    } else {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'alat'  =>  $device,
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                        ];
                        session()->flash('error', 'Data Tidak Ditemukan');
                        return view('/content/ketinggian_air/search', ['pageConfigs' => $pageConfigs], $data);
                    }
                } elseif ($kirim == "pdf") {
                    $count_device = DeviceReportModel::where("uuid_device", $device)->whereBetween('date_report', [$awal, $akhir])->where("status", "aktif")->count();
                    if ($count_device) {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'alat'  =>  $device,
                            'nama_device'   => DeviceModel::where("no", $device)->first(),
                        ];

                        return view('/content/ketinggian_air/pdf', ['pageConfigs' => $pageConfigs], $data);
                    } else {
                        $result_device = DeviceReportModel::where("uuid_device", $device)->where('status', 'aktif')->whereBetween('date_report', [$awal, $akhir])->get();
                        $pageConfigs = ['pageHeader' => false];
                        $data = [
                            'title' =>  'Laporan Ketinggian Air',
                            'result'    =>  $result_device,
                            'alat'  =>  $device,
                            'awal'  =>  $awal,
                            'akhir' =>  $akhir,
                            'device'    =>  DeviceModel::where("status_run", "1")->orderby('no', 'desc')->get(),
                        ];
                        session()->flash('error', 'Data Tidak Ditemukan');
                        return view('/content/ketinggian_air/search', ['pageConfigs' => $pageConfigs], $data);
                    }
                } else {
                    return redirect()->to('laporan_ketinggian_air/index')->with('error', "Gagal Memproses Data");
                }
            } else {
                return redirect()->to('laporan_ketinggian_air/index')->with('error', "Gagal Memproses Data");
            }
        } catch (\Throwable $th) {
            return redirect()->to('laporan_ketinggian_air/index')->with('error', "Gagal Memproses Data");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
