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

namespace Modules\Artikel\Http\Controllers;

use App\Models\Article;
use App\Models\Categori;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Contracts\Support\Renderable;
use Modules\Artikel\Services\ArtikelServiceInterface;

class ArtikelController extends Controller
{
    protected $view = 'artikel::';
    protected $table = 'ArtikelTable';
    protected $targetModal = 'app-modal';
    protected $artikelService;

    public function __construct(ArtikelServiceInterface $artikelService)
    {
        $this->artikelService = $artikelService;
    }

    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        $Artikel = Article::whereNotNull('categori_id')->get();
        $bc = breadcrumb(array(['link' => '#', 'page' => __('lang.artikel')]));

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

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        $bc = breadcrumb(array(
                                ['link' => route('artikel.index'), 'page' => __('lang.artikel')],
                                ['link' => '#', 'page' => __('lang.add_data',['data' => __('lang.artikel')])],
                            ));

        $Category = Categori::where('status', 'Y')->orderBy('id','asc')->get();

        return view($this->view. 'artikel',[
            'Category'   => $Category,
            'bc'         => $bc,
            'updateMode' => false,
            'Artikel'    => false,
            'method'     => route('artikel.store'),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        try {
            Validator::make($request->all(), [
                'category' => 'required',
                'title'    => 'required|min:10',
                'content'  => 'required|min:20',
                'status'   => 'required',
            ]);

            $this->artikelService->create([
                'categori_id'  => $request->category,
                'tittle'       => $request->title,
                'content'      => $request->content,
                'youtube'      => $request->youtube,
                'slug'         => Str::slug($request->title),
                'publish_date' => ($request->status == 'publish')?now(): NULL,
                'status'       => $request->status,
                'updated_at'   => NULL,
            ]);

            return redirect()->route('artikel.index')->with("success", __('messages.save_success', ['action' => __('lang.artikel'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show(string $hash_id)
    {

    }

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

        $Category = Categori::where('status', 'Y')->orderBy('id', 'asc')->get();
        $Artikel = $this->artikelService->findById(decryptString($hash_id));;

        return view($this->view . 'artikel', [
            'Category'   => $Category,
            'bc'         => $bc,
            'updateMode' => true,
            'Artikel'    => $Artikel,
            'method'     => route('artikel.update', ['id' => encryptString($Artikel->id)]),
        ]);
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, string $hash_id)
    {
        try {
            Validator::make($request->all(), [
                'category' => 'required',
                'title'    => 'required|min:10',
                'content'  => 'required|min:20',
                'status'   => 'required',
            ]);

            $Artikel = $this->artikelService->findById(decryptString($hash_id));
            $Artikel->update([
                'categori_id' => $request->category,
                'tittle'   => $request->title,
                'content'  => $request->content,
                'youtube'  => $request->youtube,
                'slug'     => Str::slug($request->slug),
                'status'   => $request->status,
                'publish_date'   => ($request->status == 'publish' && $Artikel->publish_date == NULL)? now(): $Artikel->publish_date,
            ]);

            return redirect()->route('artikel.index')->with("success", __('messages.update_success', ['action' => __('lang.artikel'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

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

            $Artikel = $this->artikelService->findById($id);

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

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

    /* Halaman Static */
    public function datatableHalamanStatic(Request $request)
    {
        if ($request->ajax()) {
            return $this->artikelService->datatableHalamanStatic();
        }
    }

    public function HalamanStaticIndex()
    {
        $HalamanStatic = Article::whereNull('categori_id')->get();

        $bc = breadcrumb(array(['link' => '#', 'page' => __('lang.halaman_static')]));

        return view($this->view . 'indexHalamanStatic', [
            'HalamanStatic' => $HalamanStatic,
            'bc'      => $bc,
            'table'   => $this->table,
        ]);
    }

    public function createHalamanStatic()
    {
        $bc = breadcrumb(array(
            ['link' => route('artikel.index'), 'page' => __('lang.artikel')],
            ['link' => '#', 'page' => __('lang.add_data', ['data' => __('lang.halaman_static')])],
        ));

        $Category = Categori::where('status', 'Y')->orderBy('id', 'asc')->get();

        return view($this->view . 'halaman-static', [
            'Category'   => $Category,
            'bc'         => $bc,
            'updateMode' => false,
            'Artikel'    => false,
            'method'     => route('artikel.storeHalamanStatic'),
        ]);
    }

    public function storeHalamanStatic(Request $request)
    {
        try {
            Validator::make($request->all(), [
                'title'    => 'required|min:10',
                'content'  => 'required|min:20',
                'status'   => 'required',
            ]);

            $this->artikelService->create([
                'tittle'       => $request->title,
                'content'      => $request->content,
                'youtube'      => $request->youtube,
                'slug'         => Str::slug($request->title),
                'publish_date' => ($request->status == 'publish') ? now() : NULL,
                'status'       => $request->status,
                'updated_at'   => NULL,
            ]);

            return redirect()->route('artikel.HalamanStaticIndex')->with("success", __('messages.save_success', ['action' => __('lang.halaman_static'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

    public function editHalamanStatic(string $hash_id)
    {
        $bc = breadcrumb(array(
            ['link' => route('artikel.HalamanStaticIndex'), 'page' => __('lang.halaman_static')],
            ['link' => '#', 'page' => __('lang.edit_data', ['data' => __('lang.halaman_static')])],
        ));

        $Artikel = $this->artikelService->findById(decryptString($hash_id));;

        return view($this->view . 'halaman-static', [
            'bc'         => $bc,
            'updateMode' => true,
            'Artikel'    => $Artikel,
            'method'     => route('artikel.updateHalamanStatic', ['id' => encryptString($Artikel->id)]),
        ]);
    }

    public function updateHalamanStatic(Request $request, string $hash_id)
    {
        try {
            Validator::make($request->all(), [
                'title'    => 'required|min:10',
                'content'  => 'required|min:20',
                'status'   => 'required',
            ]);

            $Artikel = $this->artikelService->findById(decryptString($hash_id));
            $Artikel->update([
                'tittle'   => $request->title,
                'content'  => $request->content,
                'youtube'  => $request->youtube,
                'slug'     => Str::slug($request->slug),
                'status'   => $request->status,
                'publish_date'   => ($request->status == 'publish' && $Artikel->publish_date == NULL) ? now() : $Artikel->publish_date,
            ]);

            return redirect()->route('artikel.HalamanStaticIndex')->with("success", __('messages.update_success', ['action' => __('lang.halaman_static'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

    public function destroyHalamanStatic(string $hash_id)
    {
        try {
            $id = decryptString($hash_id);

            $Artikel = $this->artikelService->findById($id);

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

    /* End Halaman Static */

    /* Categori */
    public function datatableKatgeori(Request $request)
    {
        if ($request->ajax()) {
            return $this->artikelService->datatableKatgeori();
        }
    }

    public function CategoryIndex()
    {
        $Category = Categori::all();

        $bc = breadcrumb(array(['link' => '#', 'page' => __('lang.category')]));

        return view($this->view . 'indexCategory', [
            'Category' => $Category,
            'bc'      => $bc,
            'table'   => $this->table,
        ]);
    }

    public function createCategory()
    {
        return response()->json([
            'html' => view($this->view . 'category', [
                'table'       => $this->table,
                'targetModal' => $this->targetModal,
                'updateMode'  => false,
                'Category'    => false,
                'method'      => route('artikel.storeCategory'),
            ])->render(),
        ]);
    }

    public function storeCategory(Request $request)
    {
        try {
            Validator::make($request->all(), [
                'name'   => 'required',
                'slug'   => 'required',
                'status' => 'required',
            ]);

            Categori::create([
                'name'       => $request->name,
                'slug'       => $request->slug,
                'status'     => $request->status,
                'updated_at' => NULL,
            ]);

            return redirect()->route('artikel.CategoryIndex')->with("success", __('messages.save_success', ['action' => __('lang.category'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

    public function editCategory(string $hash_id)
    {
        $Category = Categori::findOrFail(decryptString($hash_id));

        return response()->json([
            'html' => view($this->view . 'category', [
                'table'        => $this->table,
                'targetModal'  => $this->targetModal,
                'updateMode'   => true,
                'Category'     => $Category,
                'method'       => route('artikel.updateCategory', ['id' => encryptString($Category->id)]),
            ])->render(),
        ]);
    }

    public function updateCategory(Request $request, string $hash_id)
    {
        try {
            Validator::make($request->all(), [
                'name'   => 'required',
                'slug'   => 'required',
                'status' => 'required',
            ]);

            $Category = Categori::findOrFail(decryptString($hash_id));
            $Category->update([
                'name'       => $request->name,
                'slug'       => $request->slug,
                'status'     => $request->status,
            ]);

            return redirect()->route('artikel.CategoryIndex')->with("success", __('messages.save_success', ['action' => __('lang.category'),]));
        } catch (\Exception $e) {
            // WRITE LOG
            writeAppLog($e->getMessage(), 'error');

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

    public function destroyCategory(string $hash_id)
    {
        try {
            $Category = Categori::findOrFail(decryptString($hash_id));

            if ($Category->delete() !== FALSE) {
                return response()->json([
                    'status' => true,
                    'message' => __('messages.delete_success', ['name' => $Category->name,]),
                ]);
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => __('messages.delete_failed', ['action' => __('lang.category'),]),
            ]);
        }
    }
    /* End Categori */
}
