<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Mahasiswa;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Imports\MahasiswaImport;
use App\Exports\MahasiswasExport;
use App\Exports\TemplateMahasiswa;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class MahasiswaController extends Controller
{
    private $activeMenu = 'Home/Mahasiswa';

    public function index(Request $request)
    {
        return view('pages.portal.master.mahasiswa.index', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'Mahasiswa' => '/'
            ],
            'activeMenu' => $this->activeMenu,

        ]);
    }

    public function getListCombo(Request $request)
    {
        $mahasiswas = Mahasiswa::where('nim', 'LIKE', $request->term . '%')->get();

        $response = [];
        foreach ($mahasiswas as $mhs) {
            $response[] = array(
                'id' => $mhs->id,
                'text' => $mhs->nim . ' ' . $mhs->nama
            );
        }

        return response()->json($response);
    }

    public function list(Request $request)
    {

        // if ($req->ajax()) {
        $data = Mahasiswa::query()->orderBy('updated_at', 'desc');

        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function (Mahasiswa $mhs) {
                $actionBtn = '<a href="' . url("/mahasiswa/edit/" . $mhs->id . "") . '" class="edit btn btn-primary btn-xs"><i class="fas fa-edit fa-sm" title="Edit"></i></a> <a href="javascript:void(0)" class="delete btn btn-danger btn-xs" title="Hapus" data-toggle="modal" data-target="#del' . $mhs->id . '"><i class="fas fa-trash fa-sm"></i></a>
                    <div class="modal fade" id="del' . $mhs->id . '">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-body text-left pb-0">
                                <h4>Hapus data</h4>
                                    <p>Data yang dihapus tidak bisa dipulihkan kembali</p>
                                </div>
                                <div class="modal-footer pt-0 border-0 justify-content-end">
                                    <form action="' . url("/mahasiswa/delete/" . $mhs->id . "") . '" method="post">
                                        <input type="hidden" name="_method" value="DELETE">
                                        <input type="hidden" name="_token" value="' . csrf_token() . '">
                                        <a href="javascript:void(0)" class="btn mr-2" data-dismiss="modal">Kembali</a>
                                        <button class="btn btn-danger">Hapus</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    ';
                return $actionBtn;
            })
            ->rawColumns(['action'])
            ->make(true);
        // }

    }

    public function form(Request $request)
    {
        return view('pages.portal.master.mahasiswa.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'Mahasiswa' => '/user',
                'Form Tambah' => '/'
            ],
            'activeMenu' => $this->activeMenu,

        ]);
    }

    public function store(Request $request, Mahasiswa $user)
    {
        $rules = [
            'nim' => 'required|numeric|unique:mahasiswas',
            'nama' => 'required|min:3',
            'tgllahir' => 'required|date_format:Y-m-d',
            'program' => 'required'
        ];

        $dataValidated = $request->validate($rules);
        $dataUser = [
            'name' => $dataValidated['nama'],
            'username' => $dataValidated['nim'],
            'password' => bcrypt(Str::replace('-', '', $dataValidated['tgllahir'])),
            'role' => 'mahasiswa',
        ];

        Mahasiswa::create($dataValidated);
        User::create($dataUser);

        return redirect('/mahasiswa')->with('success', 'Data berhasil disimpan');
    }

    public function edit($id)
    {
        return view('pages.portal.master.mahasiswa.form', [
            'breadcrumb' => [
                'Home' => '/',
                'Master' => '/',
                'Mahasiswa' => '/mahasiswa',
                'Form Edit' => '/'
            ],
            'activeMenu' => $this->activeMenu,
            'data' => Mahasiswa::find($id),
            'id' => $id

        ]);
    }

    public function update(Request $request)
    {
        $mahasiswa = Mahasiswa::find($request->id);
        $rules = [
            'nama' => 'required|min:3',
            'tgllahir' => 'required|date_format:Y-m-d',
            'program' => 'required'
        ];

        if ($request->nim != $mahasiswa->nim) {
            $rules['nim'] = 'required|min:3|unique:mahasiswas';
        }

        $dataValidated = $request->validate($rules);

        $dataUser = [
            'name' => $dataValidated['nama']
        ];

        Mahasiswa::find($request->id)
            ->update($dataValidated);

        User::where('username', $request->nim)
            ->update($dataUser);


        return redirect('/mahasiswa')->with('success', 'Data berhasil disimpan');
    }

    public function destroy($id)
    {
        $mahasiswa = Mahasiswa::find($id);
        User::where('username', $mahasiswa->nim)->delete();
        Mahasiswa::destroy($id);
        return redirect('/mahasiswa')->with('success', 'Data berhasil dihapus');
    }

    function template(Request $request)
    {

        return Excel::download(new TemplateMahasiswa, 'Template-Mahasiswa.xlsx');
    }

    function import(Request $request)
    {
        $file = $request->validate([
            'file' => 'required'
        ]);
        $import = new MahasiswaImport;
        Excel::import($import, $request->file('file'));
        return back()->with('success', $import->getSuccessRowCount() . ' dari ' . $import->getRowCount() . ' data berhasil disimpan');;
    }

    function export(Request $request)
    {
        return Excel::download(new MahasiswasExport, 'Data-Mahasiswa-' . date('Ymd') . '.xlsx');
    }
}
