<?php

namespace App\Http\Controllers;

use App\Helpers\CheckLenght;
use App\Helpers\RemoveKarakter;
use App\Models\GroupDetailModel;
use App\Models\JabatanModel;
use App\Models\MessageModel;
use App\Models\PangkatModel;
use App\Models\PegawaiModel;
use App\Models\PenerimaBroadcastModel;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class PegawaiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Pegawai',
            'result'    =>  PegawaiModel::OrderBy('no', 'desc')->get(),
            'pangkat'   =>  PangkatModel::all(),
            'jabatan'   =>  JabatanModel::all(),
            'pangkat_dua'   =>  PangkatModel::all(),
            'jabatan_dua'   =>  JabatanModel::all()
        ];

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

    public function tambah_data()
    {
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Pegawai',
            'result'    =>  PegawaiModel::OrderBy('no', 'desc')->get(),
        ];

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

    public function edit_pegawai($id)
    {
        $id = RemoveKarakter::remove_method_get($id);
        $check = PegawaiModel::where("no",$id)->count();
        if(!$check || !isset($id)) {
            return redirect()->to('pegawai/index');
        }
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Pegawai',
            'main'    =>  PegawaiModel::where("no",$id)->first(),
        ];

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function ambil()
    {
        $result = PegawaiModel::OrderBy("no", "desc")->get();
        $query = DataTables::of($result)
            ->addIndexColumn()
            ->make(true);
        return $query;
    }

    public function ambil_data(Request $request)
    {
        // if ($request->ajax()) {
            $pegawai = PegawaiModel::OrderBy('no', 'desc');
            $DataTables = DataTables::of($pegawai)
                ->addIndexColumn()
                ->addColumn('nama', function ($nama) {
                    if ($nama) {
                        $name = $nama->name;
                    } else {
                        $name = '-';
                    }

                    return $name;
                })
                ->addColumn('email', function ($email) {
                    if ($email) {
                        $email = $email->email;
                    } else {
                        $email = '-';
                    }
                    return $email;
                })
                ->addColumn('nomor_whatsapp', function ($no_wa) {
                    if ($no_wa) {
                        $no_wa = $no_wa->no_wa;
                    } else {
                        $no_wa = '-';
                    }
                    return $no_wa;
                })
                ->addColumn('status', function ($status) {
                    if ($status->active == 1) {
                        $active = "<span class='badge badge badge-pill bg-success'>Aktif</span>";
                    } else {
                        $active = "<span class='badge badge badge-pill bg-danger'>Tidak Aktif</span>";
                    }
                    return $active;
                })
                ->addColumn('action', function ($action) {
                    $no = $action->no;
                    $hapus = url('pegawai/hapus_pegawai');
                    $edit = url('pegawai/edit_pegawai/' . $no);
                    $method = method_field('DELETE');
                    $csrf = csrf_field();
                    $aksi = "
                <div class='dropdown'>
                              <button type='button' class='btn btn-sm dropdown-toggle hide-arrow py-0' data-bs-toggle='dropdown'>
                              <i class='fas fa-ellipsis-vertical'></i>
                              </button>
                              <div class='dropdown-menu dropdown-menu-end'>
                                
                                <a class='dropdown-item' href='#'  data-bs-toggle='modal'
                                data-bs-target='#hapus$no'>
                                  <i  class='me-50 fas fa-trash'></i>
                                  <span>Delete</span>
                                </a>
                              </div>
                            </div>

                            <div class='modal fade' id='hapus$no' tabindex='-1' aria-hidden='true'>
  <div class='modal-dialog  modal-lg' role='document'>
    <form method='POST' enctype='multipart/form-data' class='modal-content' action='$hapus'>
      $csrf
      $method
      <div class='modal-header'>
        <input type='hidden' name='id' value='$no'>
        <h5 class='modal-title' id='modalFullTitle'>Hapus Anggota</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([
                    'nama',
                    'email',
                    'nomor_whatsapp',
                    '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->whereHas('jabatan', function ($levelQuery) use ($searchValue) {
                                $levelQuery->where('jabatan', 'LIKE', '%' . $searchValue . '%');
                            })
                            ->orWhereHas('pangkat', function ($levelQuery) use ($searchValue) {
                                $levelQuery->where('pangkat', 'LIKE', '%' . $searchValue . '%');
                            })
                            ->orWhere('name', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('jenis', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('no_hp', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('no_wa', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('eselon', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('email', 'LIKE', '%' . $searchValue . '%')
                            ->orWhere('active', 'LIKE', '%' . $searchValue . '%');
                        });
                    }
                })
                // ->make(true);
                ->toJson();
                return $DataTables;
        // } else {
        //     return abort(404);
        // }
    }

    /**
     * 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:contacts|alpha_num_dot_comma_space|integer',
            'name'  =>  'required|unique:contacts|max:255|alpha_num_dot_comma_space|string',
            'email' =>  'required|email|unique:contacts|max:100',
            'no_wa' =>  'required|unique:contacts|alpha_num_dot_comma_space',
            'status'    =>  'integer|max:2|alpha_num_dot_comma_space'
        ], [
            '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',

            'name.required' =>  'Nama Harus Di Isi',
            'name.unique'   =>  'Nama Sudah Ada',
            'name.max'  =>  'Karakter Nama Terlalu Panjang',
            'name.string'   =>  'Nama Harus String',
            'name.alpha_num_dot_comma_space'    =>  'Nama Tidak Valid',


            'email.required'    =>  'Email Harus Di Isi',
            'email.email'   =>  'Email Tidak Valid',
            'email.unique'  =>  'Email Sudah Ada',
            'email.max' =>  'Karakter Email Terlalu Panjang',

            'no_wa.required'    =>  'No Wa Harus Di Isi',
            'no_wa.unique'  =>  'No Wa Sudah Ada',
            'no_wa.alpha_num_dot_comma_space'   =>  'No Wa Tidak Valid',

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

        $kode = RemoveKarakter::hapus_karakter($request->uuid);
        $name = RemoveKarakter::hapus_karakter($request->name);
        $email = RemoveKarakter::hapus_karakter_untuk_email($request->email);
        $no_wa = RemoveKarakter::remove_method_get($request->no_wa);


        $leng_kode = CheckLenght::lenght($request->uuid);
        $leng_no_wa = CheckLenght::lenght($request->no_wa);
        if ($leng_kode > 255) {
            return redirect()->back()->with('error', 'Karakter kode terlalu panjang');
        }
        
        if ($leng_no_wa > 14) {
            return redirect()->back()->with('error', 'Karakter No Wa terlalu panjang');
        }

        try {
            $status = RemoveKarakter::remove_method_get($request->active);
            if ($status) {
                if ($status == 1) {
                    $active = "1";
                } else {
                    $active = "0";
                }
            } else {
                $active = "0";
            }
            $pegawai = new PegawaiModel();
            $pegawai->uuid = $kode;
            $pegawai->name = $name;
            $pegawai->email = $email;
            $pegawai->no_wa = $no_wa;
            $pegawai->active = $active;
            $pegawai->save();
            return redirect()->to('pegawai/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($id)
    {
        //
    }

    /**
     * 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([
            'name'  =>  'required|max:255|alpha_num_dot_comma_space|string',
            'nip_nik'   =>  'required|alpha_num_dot_comma_space|integer',
            'jenis' =>  'required|alpha_num_dot_comma_space',
            'uuid_pangkat'  =>  'required|alpha_num_dot_comma_space|integer',
            'uuid_jabatan'  =>  'required|alpha_num_dot_comma_space|integer',
            'eselon'    =>  'required|alpha_num_dot_comma_space|integer',
            'email' =>  'required|email|max:100',
            'no_hp' =>  'required|alpha_num_dot_comma_space',
            'no_wa' =>  'required|alpha_num_dot_comma_space',
            'status'    =>  'integer|max:2|alpha_num_dot_comma_space'
        ], [
            'name.required' =>  'Nama Harus Di Isi',
            'name.max'  =>  'Karakter Nama Terlalu Panjang',
            'name.string'   =>  'Nama Harus String',
            'name.alpha_num_dot_comma_space'    =>  'Nama Tidak Valid',

            'nip_nik.required'  =>  'Nip Harus Di Isi',
            'nip_nik.alpha_num_dot_comma_space' =>  'Nip Tidak Valid',
            'nip_nik.integer'   =>  'Nip Harus Integer',

            'jenis.required'    =>  'Jenis Harus Di Isi',
            'jenis.alpha_num_dot_comma_space'   =>  'Jenis Tidak Valid',

            'uuid_pangkat.required'  =>  'Pangkat Harus Di Isi',
            'uuid_pangkat.integer'  =>  'Pangkat Harus Integer',
            'uuid_pangkat.alpha_num_dot_comma_space'    =>  'Pangkat Tidak Valid',

            'uuid_jabatan.required'  =>  'Jabatan Harus Di Isi',
            'uuid_jabatan.integer'  =>  'Jabatan Harus Integer',
            'uuid_jabatan.alpha_num_dot_comma_space'    =>  'Jabatan Tidak Valid',

            'eselon.required'   =>  'Eselon Harus Di Isi',
            'eselon.alpha_num_dot_comma_space'  =>  'Eselon Tidak Valid',
            'eselon.integer'    =>  'Eselon Harus Integer',

            'email.required'    =>  'Email Harus Di Isi',
            'email.email'   =>  'Email Tidak Valid',
            'email.max' =>  'Karakter Email Terlalu Panjang',

            'no_hp.required'    =>  'No Hp Harus Di Isi',
            'no_hp.alpha_num_dot_comma_space'   =>  'No Hp Tidak Valid',

            'no_wa.required'    =>  'No Wa Harus Di Isi',
            'no_wa.alpha_num_dot_comma_space'   =>  'No Wa Tidak Valid',

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

        $name = RemoveKarakter::hapus_karakter($request->name);
        $nip_nik = RemoveKarakter::hapus_karakter($request->nip_nik);
        $jenis = RemoveKarakter::hapus_karakter($request->jenis);
        $uuid_pangkat = RemoveKarakter::hapus_karakter($request->uuid_pangkat);
        $uuid_jabatan = RemoveKarakter::hapus_karakter($request->uuid_jabatan);
        $eselon = RemoveKarakter::hapus_karakter($request->eselon);
        $email = RemoveKarakter::hapus_karakter_untuk_email($request->email);
        $no_hp = RemoveKarakter::remove_method_get($request->no_hp);
        $no_wa = RemoveKarakter::remove_method_get($request->no_wa);

        $leng_nip = CheckLenght::lenght($request->nip_nik);
        $leng_eselon = CheckLenght::lenght($request->eselon);
        $leng_no_hp = CheckLenght::lenght($request->no_hp);
        $leng_no_wa = CheckLenght::lenght($request->no_wa);

        if ($leng_nip > 20) {
            return redirect()->back()->with('error', 'Karakter Nip terlalu panjang');
        }
        if ($leng_eselon > 2) {
            return redirect()->back()->with('error', 'Karakter Eselon terlalu panjang');
        }
        if ($leng_no_hp > 14) {
            return redirect()->back()->with('error', 'Karakter No Hp terlalu panjang');
        }
        if ($leng_no_wa > 14) {
            return redirect()->back()->with('error', 'Karakter No Wa terlalu panjang');
        }
        $id = RemoveKarakter::remove_method_get($request->id);
        $check = PegawaiModel::where("no", $id)->count();
        if (!$check || !isset($id)) {
            return redirect()->back()->with("error", "Data Gagal Diupdate");
        }
        try {
            $status = RemoveKarakter::remove_method_get($request->active);
            if ($status) {
                if ($status == 1) {
                    $active = "1";
                } else {
                    $active = "0";
                }
            } else {
                $active = "0";
            }
            PegawaiModel::where("no", $id)->update([
                'name'  =>  $name,
                'nip_nik'   =>  $nip_nik,
                'jenis' =>  $jenis,
                'uuid_pangkat'  =>  $uuid_pangkat,
                'uuid_jabatan'  =>  $uuid_jabatan,
                'eselon'    =>  $eselon,
                'email' =>  $email,
                'no_hp' =>  $no_hp,
                'no_wa' =>  $no_wa,
                'active'    =>  $active
            ]);
            return redirect()->to('pegawai/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 = PegawaiModel::where("no", $id)->count();
        if (!$check || !isset($id)) {
            return redirect()->back()->with("error", "Data Gagal Dihapus");
        }
        try {
            $result = GroupDetailModel::where("uuid_contact", $id)->count();
            $dua = PenerimaBroadcastModel::where("uuid_contacts", $id)->where('deleted_at', null)->count();
            if ($result || $dua) {
                return redirect()->back()->with("error", "Data ini tidak boleh dihapus karena sudah berelasi");
            }
            PegawaiModel::where("no", $id)->delete();
            return redirect()->back()->with("success", "Data Berhasil Dihapus");
        } catch (\Throwable $th) {
            return redirect()->back()->with("error", "Data Gagal Dihapus");
        }
    }
}
