<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

use DataTables;
use GuzzleHttp\Client;
use Carbon\Carbon;

use App\Models\Kriteria;
use App\Models\Nilai;

class KriteriaController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Kriteria::select('*');
            // Convert the Eloquent Collection to a regular PHP array
            $data->each(function ($item, $key) {
                $item->rowIndex = $key + 1;
            });

            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('title-post', function($row){
                    $text = '
                    <p class="mb-0">' . $row->kriteria . '</p>
                    ';
                    return $text;
                })
                ->rawColumns(['title-post'])
                ->make(true);
        }

        $data = [
            'subtitle' => 'Kriteria',
            'button' => true,
            'module' => [
                'url' => route('kriteria.create'),
                'name' => 'Tambah Baru'
            ]
        ];

        return view('admin.app.content.kriteria.index', compact('data'));
    }

    public function create()
    {
        $data = [
            'subtitle' => 'Tambah baru',
        ];

        $bobot = Nilai::all();
        return view('admin.app.content.kriteria.add', compact('data', 'bobot'));
    }

    /**
     * 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(), [
            'id_kriteria' => 'required',
            'nama_kriteria' => 'required',
        ]);

        if ($validator->fails()) {
           return redirect()->back()->withInput()->with('error', 'Terjadi kesalahan, silakan coba lagi. Code: ' . $validator->errors()->first());
        }

        $input = $request->all();

        $post = new Kriteria([
            'id_kriteria' => $input['id_kriteria'], // Membersihkan input judul menggunakan Purifier
            'nama_kriteria' => $input['nama_kriteria'], // Membersihkan input deskripsi menggunakan Purifier
        ]);

        $check = Kriteria::where('nama_kriteria', $input['nama_kriteria'])->count();
        if ($check == 0) {
            if ($post->save()) {
                return redirect()->route('kriteria')->with('success', 'Berhasil tambah data kriteria');
            } else {
                return redirect()->route('kriteria')->with('error', 'Terjadi kesalahan dalam query.');
            }
        } else {
            return redirect()->route('kriteria')->with('error', 'Data sudah ada');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = [
            'subtitle' => 'Edit: ' . Kriteria::where('id_kriteria', $id)->first()->title,
        ];

        $kriteria = Kriteria::FindOrFail($id);
        $bobot = Nilai::all();

        return view('admin.app.content.kriteria.edit', compact('data','kriteria', 'id', 'bobot'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Validasi input sebelum memperbarui data
        $validator = Validator::make($request->all(), [
            'id_kriteria' => 'required',
            'nama_kriteria' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withInput()->with('error', 'Unexpected error, please try again. code: ' . $validator->errors()->first());
         }

        // Cari data berdasarkan ID
        $kriteria = Kriteria::find($id);

        // Jika data ditemukan
        if ($kriteria) {

            // Update data dengan data baru dari form yang telah dibersihkan
            $kriteria->id_kriteria = $request->input('id_kriteria');
            $kriteria->nama_kriteria = $request->input('nama_kriteria');
            // Simpan perubahan pada database
            $kriteria->save();
            return redirect()->route('kriteria')->with('success', 'You are successfully added new records');
        } else {
            return redirect()->route('kriteria')->with('error', 'Unexpected error');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // Cari data berdasarkan ID
        $kriteria = Kriteria::find($id);
        // Jika data ditemukan
        if ($kriteria) {
            // Hapus data dari database
            $kriteria->delete();
            return redirect()->route('kriteria')->with('success', 'Data kriteria berhasil dihapus');
        } else {
            return redirect()->route('kriteria')->with('error', 'Data kriteria gagal dihapus');
        }
    }
}
