<?php

namespace App\Http\Controllers;

use App\GeneralPrefrence;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class GeneralPreferencesController extends Controller
{

    protected string $module = 'General Preferences';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }

    public function index()
    {
        $pref = GeneralPrefrence::all();

        return view('general_preferences.index', compact('pref'));
    }

    public function create()
    {
        return view('city.create');
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'rate' => 'nullable|string|max:255',
            'amount_type' => 'nullable|string|max:255',
        ]);

        $pref = new GeneralPrefrence();
        $pref->name = $validatedData['name'];
        $pref->rate = $validatedData['rate'];
        $pref->amount_type = $validatedData['amount_type'];
        $pref->status = '1';
        $pref->save();

        Session::flash('message', 'General Preferrences has been added');
        return redirect(url('general_preferences'));
    }


    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            // 'name' => 'required|string|max:255',
            'rate' => 'nullable|string|max:255',
            'amount_type' => 'nullable|string|max:255',
        ]);

        $pref = GeneralPrefrence::findOrFail($id);
        // dd($id);

        // $pref->name = $validatedData['name'];
        $pref->rate = $validatedData['rate'];
        $pref->amount_type = $validatedData['amount_type'];

        $pref->save();

        Session::flash('message', 'General Preferences has been updated successfully');

        return redirect(url('general_preferences'));
    }

    public function destroy($id)
    {
        $city_id = Crypt::decrypt($id);
        $city = City::findOrFail($city_id);

        if ($city) {
            $city->delete();
            Session::flash('message', 'City has been deleted');
        } else {
            Session::flash('message', 'City not found');
        }

        return redirect(url('cities'));
    }

    //
}
