<?php
/*=========================================================================================
    App Name  : PPID PTUN Semarang
    File Name : PermohonanController
    --------------------------------------------------------------------------------------
    Author    : Fuad Auliya Rohman
    Email     : fuad.dev16@gmail.com
==========================================================================================*/

namespace Modules\Permohonan\Http\Controllers;

use App\Events\Permohonan as EventsPermohonan;
use App\Models\User;
use App\Models\Permohonan;
use App\Libraries\Constants;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\DokumenPermohonanPPID;
use Illuminate\Support\Facades\Storage;
use Illuminate\Contracts\Support\Renderable;
use Modules\Permohonan\Services\PermohonanServiceInterface;

class PermohonanController extends Controller
{
    protected $view = 'permohonan::';
    protected $table = 'PermohonanTable';
    protected $targetModal = 'app-modal';
    protected $permohonanService;

    public function __construct(PermohonanServiceInterface $permohonanService)
    {
        $this->permohonanService = $permohonanService;
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $bc = breadcrumb(array(['link' => '#', 'page' => __('lang.application')]));
        $Permohonan = $this->permohonanService->all();

        return view($this->view . 'index', [
            'bc' => $bc,
            'Permohonan' => $Permohonan,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('permohonan::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show(string $hash_id)
    {
        try {
            $bc = breadcrumb(array(
                ['link' => route('user.permohonan'), 'page' => __('lang.application')],
                ['link' => '#', 'page' => __('lang.detail_data', ['data' => __('lang.application')])],
            ));

            $Permohonan = $this->permohonanService->findById(decryptString($hash_id));
            $DokumenPermohonanPPID = DokumenPermohonanPPID::where('permohonan_id', $Permohonan->id)->get();

            return view($this->view . 'show', [
                'bc' => $bc,
                'Permohonan' => $Permohonan,
                'DokumenPermohonanPPID' => $DokumenPermohonanPPID,
            ]);
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

            return redirect()->back()->with("failed", __('messages.action_message', ['action' => __('lang.detail'), 'message' => __('lang.application')]));
        }
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit(string $hash_id)
    {
        $bc = breadcrumb(array(
            ['link' => route('permohonan.index'), 'page' => __('lang.application')],
            ['link' => '#', 'page' => __('lang.edit_data', ['data' => __('lang.application')])],
        ));

        $Permohonan = $this->permohonanService->findById(decryptString($hash_id));
        $Anggota = User::where('id', $Permohonan->user_id)->first();

        return view($this->view.'edit',[
            'bc' => $bc,
            'Permohonan' => $Permohonan,
            'Anggota' => $Anggota,
            'method' => route('permohonan.update', ['id' => encryptString($Permohonan->id)]),
            'updateMode' => true,
        ]);
    }

    /**
     * Update tzhze specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, string $hash_id)
    {
        try {
            $request->validate([
                'jenis_permohonan'    => 'required',
                'ket_permohonan_info' => 'required',
            ]);

            $Permohonan = $this->permohonanService->findById(decryptString($hash_id));

            $userPath = getUploadPath() . config('ppid.permohonan');
            $validFileExtension = ['pdf'];
            if ($request->dokumen_permohonan != NULL) {
                $PermohonanName = $request->dokumen_permohonan->getClientOriginalName();
                $PermohonanExtension = $request->dokumen_permohonan->getClientOriginalExtension();
                $PermohonanSize = convertFileSize($request->dokumen_permohonan->getSize());
                $newNamePermohonan = Constants::FILE_PERMOHONAN_NAME . time() . '.' . $PermohonanExtension;

                // VALIDATION EXTENSION
                if (!in_array(strtolower($PermohonanExtension), $validFileExtension)) {
                    throw new \Exception(__('validation.file', ['attribute' => __('lang.file'),]));
                }

                // VALIDATION FILE SIZE
                if ($PermohonanSize > getSetting('max_file_upload')) {
                    throw new \Exception(__('validation.max.file', ['attribute' => __('lang.file'), 'max' => config('ppid.max_file_upload'),]));
                }

                //DELETE FILE
                if (Storage::exists($userPath . $Permohonan->file)) {
                    Storage::delete($userPath . $Permohonan->file);
                }

                // UPLOAD
                Storage::putFileAs($userPath, $request->dokumen_permohonan, $newNamePermohonan);

                $Permohonan->update([
                    'jenis_form_layanan_id'    => decryptString($request->jenis_permohonan),
                    'nama_institusi'           => $request->institusi,
                    'isi_permintaan_informasi' => $request->ket_permohonan_info,
                    'file'                     => $newNamePermohonan,
                ]);
            }else{
                $Permohonan->update([
                    'jenis_form_layanan_id'    => decryptString($request->jenis_permohonan),
                    'nama_institusi'           => $request->institusi,
                    'isi_permintaan_informasi' => $request->ket_permohonan_info,
                ]);
            }

            if ($Permohonan == TRUE) {
                return redirect()->route('permohonan.show',['id' => encryptString($Permohonan->id)])->with("success", __('messages.update_success', ['action' => __('lang.edit'),]));
            }
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

            return redirect()->back()->with("failed", __('messages.update_failed', ['action' => __('lang.edit'),]));
        }
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy(string $hash_id)
    {
        try {
            $Permohonan = $this->permohonanService->findById(decryptString($hash_id));

            if ($Permohonan->delete() !== FALSE) {
                $userPath = getUploadPath() . config('ppid.permohonan');
                //DELETE FILE
                if (Storage::exists($userPath . $Permohonan->file)) {
                    Storage::delete($userPath . $Permohonan->file);
                }

                return response()->json([
                    'status' => true,
                    'message' => __('messages.delete_success', ['name' => __('lang.application'),]),
                ]);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => __('messages.delete_failed', ['action' => __('lang.application'),]),
            ]);
        }
    }

    public function datatable(Request $request)
    {
        if ($request->ajax()) {
            return $this->permohonanService->datatable();
        }
    }

    /* JAWABAN */
    public function addJawaban(string $PermohonanID)
    {
        $Permohonan = $this->permohonanService->findById(decryptString($PermohonanID));

        return response()->json([
            'html' => view($this->view . 'modal-jawaban', [
                'table'      => $this->table,
                'method'     => route('permohonan.postJawaban', ['id' => encryptString($Permohonan->id)]),
                'updateMode' => false,
                'Permohonan' => $Permohonan,
            ])->render(),
        ]);
    }

    public function postJawaban(string $PermohonanID, Request $request)
    {
        try {
            $Permohonan = $this->permohonanService->findById(decryptString($PermohonanID));

            $Permohonan->update([
                'jawaban' => $request->jawaban,
                'status_id' => ($request->jawaban !== NULL) ? '2' : '3',
                'status_text' => ($request->jawaban !== NULL)? 'Perbaikan Permohonan':'Perbaikan Sudah Diterima',
            ]);

            // SEND NOTIFICATION
            event(new EventsPermohonan($Permohonan));

            if ($Permohonan == TRUE) {
                return redirect()->route('permohonan.show', ['id' => encryptString($Permohonan->id)])->with("success", __('messages.update_success', ['action' => __('lang.jawaban'),]));
            }
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

            return redirect()->back()->with("failed", __('messages.update_failed', ['action' => __('lang.jawaban'),]));
        }
    }

    public function getPermohonan(string $PermohonanID, string $statusPermohonan)
    {
        try {
            $Permohonan = $this->permohonanService->findById(decryptString($PermohonanID));

            //4 = Permohonan Diterima , 5 = Dokumen Permohonan Diterbitkan , 8 = Dokumen Permohonan Ditolak
            $StatusPermohonan = decryptString($statusPermohonan);

            if($StatusPermohonan == 4){
                $StatusPermohonanText = 'Permohonan Diterima';
            }elseif($StatusPermohonan == 8){
                $StatusPermohonanText = 'Permohonan Ditolak';
            }

            $Permohonan->update([
                'status_id' => $StatusPermohonan,
                'status_text' => $StatusPermohonanText,
            ]);

            // SEND NOTIFICATION
            event(new EventsPermohonan($Permohonan));

            if ($Permohonan == TRUE) {
                return redirect()->route('permohonan.show', ['id' => encryptString($Permohonan->id)])->with("success", __('messages.update_success', ['action' => __('lang.application'),]));
            }
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

            return redirect()->back()->with("failed", __('messages.update_failed', ['action' => __('lang.application'),]));
        }
    }

}
