<?php

namespace App\Http\Controllers\Admin;

use App\Exports\MsFormasiExport;
use App\Http\Controllers\Controller;
use App\Models\MsFormasi;
use App\Models\MsJenisFormasi;
use App\Models\MsProdi;
use App\Models\MsPropinsi;
use App\Models\MsProvinsi;
use App\Models\MsRefSms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
use Excel;
use Exception;

class FormasiController extends Controller
{
    private $indexRoute = null;

    public function __construct(){
        $this->indexRoute = route('formasi.index');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['formasi'] = MsFormasi::query()
        ->with('prodi.jenjangPendidikan')
        ->select([
            'ms_formasi.*',
            // 'formasi_prodi.prodi_id'
            DB::raw("COUNT(formasi_prodi.prodi_id) AS jumlah_prodi")
        ])
        ->leftJoin('formasi_prodi', 'ms_formasi.id', '=', 'formasi_prodi.formasi_id')
        ->orderBy('kode')
        ->orderBy('nama')
        ->orderBy('penempatan')
        ->groupBy('ms_formasi.id')
        ->get();

        $data['ms_jenis_formasi'] = MsJenisFormasi::query()->get();
        $data['msProdi'] = MsRefSms::query()->orderBy('nama')->get();
        // dd($data);
        return view('content.backend.masters.formasi.index', $data);
    }

    public function excel()
    {
        return Excel::download(new MsFormasiExport, 'formasi.xlsx');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), MsFormasi::RULES, MsFormasi::ERROR_MESSAGE);

        if ($validator->fails())
        {
            $errormessage = $validator->messages();

            return redirect()
            ->back()
            ->withErrors($validator)
            ->withInput();
        }

        $data = $request->except('_token');
        $data['urutan'] = MsFormasi::getUrutan();
        $data['kode'] = date("y").sprintf('%03d', $data['urutan']);
        $data['jenis_formasi_id'] = decrypt($data['jenis_formasi_id']);

        MsFormasi::query()->create($data);

        return redirect()->intended($this->indexRoute)->with('success', 'Berhasil menambahkan data');
    }

    /**
     * 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)
    {
        $data['formasi'] = MsFormasi::query()->find(decrypt($id));
        $data['ms_jenis_formasi'] = MsJenisFormasi::query()->get();

        return view('content.backend.masters.formasi.edit', $data);
    }

    public function editProdi($id)
    {
        $data['formasi'] = MsFormasi::query()->with('prodi')->find(decrypt($id));
        $data['prodi'] = MsRefSms::query()->with('jenjangPendidikan')->orderBy('nama')->get();

        return view('content.backend.masters.formasi.edit_prodi', $data);
    }

    public function updateProdi(Request $request, $id)
    {
        $formasi = MsFormasi::query()->find(decrypt($id));
        $prodi = $request->prodi;
        $arrProdi = [];

        if(!is_null($prodi)){
            foreach($prodi as $key => $item){
                $arrProdi[] = decrypt($key);
            }
        }

        $formasi->prodi()->sync($arrProdi);
        return redirect()->intended($this->indexRoute)->with('success', 'Berhasil mengupdate prodi');
    }

    public function storeProdi(Request $request)
    {
        $data['formasi'] = MsFormasi::query()->find(decrypt($request->formasi_id));
        $data['prodi'] = MsRefSms::query()
        ->with('jenjangPendidikan')
        ->find(decrypt($request->prodi_id));

        $data['formasi']->prodi()->attach([$data['prodi']->id]);

        return view('content.backend.masters.formasi.row_prodi', $data);
    }

    public function deleteProdi(Request $request)
    {
        $data['formasi'] = MsFormasi::query()->find(decrypt($request->formasi_id));
        $data['prodi'] = MsRefSms::query()
        ->with('jenjangPendidikan')
        ->find(decrypt($request->prodi_id));

        $data['formasi']->prodi()->detach([$data['prodi']->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)
    {
        $validator = Validator::make($request->all(), MsFormasi::RULES, MsFormasi::ERROR_MESSAGE);

        if ($validator->fails())
        {
            $errormessage = $validator->messages();

            return redirect()
            ->back()
            ->withErrors($validator)
            ->withInput();
        }

        try{
            $formasi = MsFormasi::query()->find(decrypt($id));
            $data = $request->except('_token');
            $data['wajib_s1'] = $request->wajib_s1;
            $data['wajib_s2'] = $request->wajib_s2;
            $data['jenis_formasi_id'] = decrypt($data['jenis_formasi_id']);

            $formasi->update($data);

            return redirect()->intended($this->indexRoute)->with('success', 'Berhasil mengupdate data');
        }
        catch(Exception $ex){
            return redirect()->intended($this->indexRoute)->withErrors(['error' => 'Gagal mengupdate data']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $formasi = MsFormasi::query()->find(decrypt($id))->delete();
        return response('Berhasil menghapus data!', 200);
    }
}
