<?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\Penyakit;
use App\Models\Gejala;
use App\Models\Rule;

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

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

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

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

        $penyakit = Penyakit::all();
        return view('admin.app.content.rule.add', compact('data', 'penyakit'));
    }

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

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

        $input = $request->all();

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

        $check = Rule::where('kode_rule', $input['kode_gejala'])->count();
        if ($check == 0) {
            if ($post->save()) {
                return redirect()->route('rule')->with('success', 'You have successfully added data');
            } else {
                return redirect()->route('rule')->with('error', 'An error occurred in the query');
            }
        } else {
            return redirect()->route('rule')->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: ' . Rule::where('id_rule', $id)->first()->title,
        ];
        $penyakit = Penyakit::all();
        $rule = Rule::find($id);

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

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

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

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

        // Jika data ditemukan
        if ($gejala) {

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