<?php

namespace App\Http\Controllers;

use App\Helpers\RemoveKarakter;
use App\Models\LevelModel;
use App\Models\User;
use Error;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class LevelController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        $level = session()->get('level');
        if($level != "Administrator") {
            return redirect()->to('dashboard/analytics');
        }
        $pageConfigs = ['pageHeader' => false];
        $data = [
            'title' =>  'Level',
            'result'    =>  LevelModel::all(),
        ];

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $level = session()->get('level');
        if($level != "Administrator") {
            return redirect()->to('dashboard/analytics');
        }
        $request->validate([
            'level' =>  'required|max:255|unique:user_level|alpha_num_dot_comma_space|string'
        ],
    [
        'required'  =>  'Nama Level Harus Di Isi',
        'max'   =>  'Karakter Nama Level Terlalu Panjang',
        'unique'    =>  'Nama Level Sudah Ada',
        'alpha_num_dot_comma_space' =>  'Nama Level Tidak Valid',
        'string'    =>  'Nama Level Harus String'
    ]);

        $level = RemoveKarakter::hapus_karakter($request->level);

        try {
            $insert  = new LevelModel();
            $insert->level = $level;
            $insert->save();
            return redirect()->back()->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 ambil_data(Request $request)
    {
        $level = session()->get('level');
        if($level != "Administrator") {
            return redirect()->to('dashboard/analytics');
        }
        if($request->ajax()) {
            $level = LevelModel::orderby('uuid','desc');
            $DataTables = DataTables::of($level) 
            ->addIndexColumn()
            ->addColumn('level',function($level) {
                if($level) {
                    $nama = $level->level;
                } else {
                    $nama = '-';
                }

                return $nama;
            })
            ->addColumn('action',function($action) {
                if($action) {
                    $no = $action->uuid;
                    $method_edit = method_field('PUT');
                    $method_hapus = method_field('DELETE');
                    $csrf = csrf_field();
                    $hapus = url("level/hapus_level");
                    $edit =url("level/edit_level");
                    if($action->level != "Administrator") {
                        $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='#edit$no'>
                        <i class='me-50 fas fa-pen'></i>
                        <span>Edit</span>
                      </a>
                      <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='edit$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='$edit'>
      $csrf
      $method_edit
      <input type='hidden' name='id' value='$no'>
      <div class='modal-header'>
        <h5 class='modal-title' id='modalFullTitle'>Edit Level</h5>
        <button type='button' class='btn-close' data-bs-dismiss='modal' aria-label='Close'></button>
      </div>
      <div class='modal-body'>
        <div class='containers'>
            <div class='mb-1'>
                <label style='margin-bottom: 5px !important;'> <h5>Nama Level*</h5></label>
              <div class='input-group'>
                <input
                  type='text'
                  class='form-control'
                  placeholder='Nama Level'
                   name='level'
                required
                value='$action->level'
                />
              </div>
              </div>
        </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'>Simpan</button>
      </div>
    </form>
  </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_hapus
      <div class='modal-header'>
        <input type='hidden' name='id' value='$no'>
        <h5 class='modal-title' id='modalFullTitle'>Hapus Level</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>

                        ";
                    } else {
                        $aksi = '';
                    }
                } else {
                    $aksi = '-';
                }
                return $aksi;
            })
            ->rawColumns([
                'level',
                '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('user_level.level', 'LIKE', '%' . $searchValue . '%');
                    });
                }
            })
            ->toJson();
            // ->make(true);
            return $DataTables;
        } else {
            abort(404);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit_level(Request $request)
    {
        $level = session()->get('level');
        if($level != "Administrator") {
            return redirect()->to('dashboard/analytics');
        }
        $request->validate([
            'level' =>  'required|max:255|unique:user_level|alpha_num_dot_comma_space|string'
        ],
    [
        'required'  =>  'Nama Level Harus Di Isi',
        'max'   =>  'Karakter Nama Level Terlalu Panjang',
        'unique'    =>  'Nama Level Sudah Ada',
        'alpha_num_dot_comma_space' =>  'Nama Level Tidak Valid',
        'string'    =>  'Nama Level Harus String'
    ]);

        $id = RemoveKarakter::remove_method_get($request->id);
        $check = LevelModel::where("uuid",$id)->count();
        if(!$check || !isset($id)) {
            return redirect()->back()->with('error','Data gagal diupdate');
        }

        $id_user = RemoveKarakter::remove_method_get(session()->get('id'));
        
        $level = RemoveKarakter::hapus_karakter($request->level);
        
        try {
            LevelModel::where('uuid',$id)->update([
                'level' =>  $level
            ]);

            $users = User::where("uuid_level",$id)->where('no',$id_user)->count();
            
            if($users) {
                session()->forget('level');
    
                $end = LevelModel::where("uuid",$id)->first();
    
                session([
                    'level' => $end->level
                ]);
            }
            return redirect()->back()->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 hapus_level(Request $request)
    {
        $level = session()->get('level');
        if($level != "Administrator") {
            return redirect()->to('dashboard/analytics');
        }
        $id = RemoveKarakter::remove_method_get($request->id);
        $check = LevelModel::where("uuid",$id)->count();
        if(!$check ||  !isset($id)) {
            return redirect()->back()->with('error',"Data Gagal Dihapus");
        }
        $result = User::where("uuid_level",$id)->count();
        if($result) {
            return redirect()->back()->with('error',"Data Ini Tidak Boleh Dihapus Karena Sudah Berelasi");
        }
        $check_satu = LevelModel::where("uuid",$id)->first();
        if($check_satu->level == "Administrator") {
            return redirect()->back()->with('error','Level Administrator Tidak Boleh Di Hapus');
        }
        try {
            LevelModel::where('uuid',$id)->delete();
            return redirect()->back()->with("success","Data Berhasil Dihapus");
        } catch (\Throwable $th) {
            return redirect()->back()->with("error","Data Gagal Dihapus");
        }
    }
}
