<?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\Gejala;

class GejalaController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Gejala::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->gejala . '</p>
                    ';
                    return $text;
                })
                ->rawColumns(['title-post'])
                ->make(true);
        }

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

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

    public function create()
    {
        $data = [
            'subtitle' => 'Tambah baru',
        ];
        return view('admin.app.content.gejala.add', compact('data'));
    }

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

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

        $input = $request->all();

        $post = new Gejala([
            'gejala' => $input['gejala'], // Membersihkan input judul menggunakan Purifier
            'kode_gejala' => $input['kode_gejala'], // Membersihkan input deskripsi menggunakan Purifier
        ]);

        $check = Gejala::where('gejala', $input['gejala'])->count();
        if ($check == 0) {
            if ($post->save()) {
                return redirect()->route('gejala')->with('success', 'You have successfully added data');
            } else {
                return redirect()->route('gejala')->with('error', 'An error occurred in the query');
            }
        } else {
            return redirect()->route('gejala')->with('error', 'Title already exists');
        }
    }

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

        return view('admin.app.content.gejala.edit', compact('data','gejala', '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)
    {
        // Validasi input sebelum memperbarui data
        $validator = Validator::make($request->all(), [
            'gejala' => 'required',
            'kode_gejala' => 'required',
        ]);

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

        // Cari data berdasarkan ID
        $gejala = Gejala::find($id);

        // Jika data ditemukan
        if ($gejala) {

            // Update data dengan data baru dari form yang telah dibersihkan
            $gejala->gejala = $request->input('gejala');
            $gejala->kode_gejala = $request->input('kode_gejala');
            // Simpan perubahan pada database
            $gejala->save();
            return redirect()->route('gejala')->with('success', 'You are successfully added new records');
        } else {
            return redirect()->route('gejala')->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
        $post = Gejala::find($id);
        // Jika data ditemukan
        if ($post) {
            // Hapus data dari database
            $post->delete();
            return redirect()->route('gejala')->with('success', 'You are successfully deleted records');
        } else {
            return redirect()->route('gejala')->with('error', 'Data not found');
        }
    }
}
