<?php

namespace Modules\Lpj\Http\Controllers;

use Exception;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Modules\Lpj\Models\JenisPenilaian;
use Modules\Lpj\Http\Requests\JenisPenilaianRequest;
use Modules\Lpj\Exports\JenisPenilaianExport;
use Maatwebsite\Excel\Facades\Excel;

class JenisPenilaianController extends Controller
{
    public $user;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::jenis_penilaian.index');
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(JenisPenilaianRequest $request)
    {
        $validate = $request->validated();

        try {
            JenisPenilaian::create($validate);
            return redirect()->route('basicdata.jenis-penilaian.index')->with('success', 'Jenis Penilaian created successfully');
        } catch (Exception $e) {
            return redirect()->route('basicdata.jenis-penilaian.create')->with('error', $e->getMessage());
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $jenisPenilaian = JenisPenilaian::find($id);
        return view('lpj::jenis_penilaian.form', compact('jenisPenilaian'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(JenisPenilaianRequest $request, $id)
    {

        $validated  = $request->validated();


        if ($validated) {
            try {
                $jenisPenilaian = JenisPenilaian::find($id);
                $jenisPenilaian->update($validated);
                return redirect()->route('basicdata.jenis-penilaian.index')->with('success', 'Jenis Penilaian updated successfully');
            } catch (Exception $e) {
                return redirect()->route('basicdata.jenis-penilaian.edit', $id)->with('error', $e->getMessage());
            }
        }

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        try {
            $jenisPenilaian = JenisPenilaian::find($id);
            $jenisPenilaian->delete();
            echo json_encode(['success' => true, 'message' => 'Jenis Penilaian deleted successfully']);

        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Failed to delete Jenis Penilaian']);
        }
    }

    public function dataForDatatables(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('jenis_penilaian.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        $query = JenisPenilaian::query();

        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('code', 'LIKE', "%$search%");
                $q->orWhere('name', 'LIKE', "%$search%");
            });
        }

        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        $totalRecords = $query->count();


        $size = $request->get('size');
        $pageCount = 1;

        if ($size > 0) {
            if ($request->has('page') && $request->has('size')) {
                $page = $request->get('page');
                $offset = ($page - 1) * $size;
                $query->skip($offset)->take($size);
                $filteredRecords = $query->count();
                $pageCount = ceil($totalRecords / $size);
            }

            $data = $query->get();
        } else {
            $filteredRecords = $totalRecords;
            $data = $query->get();
        }

        $currentPage = $request->get('page') ?? 1;


        // Return the response data as a JSON object
        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $currentPage,
            'totalCount'      => $totalRecords,
            'data'            => $data
        ]);
    }


    public function export()
    {
        return Excel::download(new JenisPenilaianExport(), 'jenis-penilaian.xlsx');
    }
}
