<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Currency;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CurrencyController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Currency List', ['only' => ['index']]);
        $this->middleware('permission:Currency Create', ['only' => ['store']]);
        $this->middleware('permission:Currency Edit', ['only' => ['store']]);
        $this->middleware('permission:Currency Delete', ['only' => ['destroy']]);
    }
    public function index(Request $request)
    {
        $per_page = $request->per_page == null?25: $request->per_page;
        $data = Currency::paginate($per_page);
        return $data;
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $currency = Currency::find($request->id);
        if($currency){
            $res = [
                'status' => 1,
                'message'=> 'Create currency success',
                'data'   => $currency,
            ];
        }else{
            $res = [
                'status'  => 0,
                'message' => 'Create currency not found',
                'data'    => [],
            ];
        }
        return response()->json($res,200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'currency_en' => 'nullable|required',
            'currency_km' => 'nullable|required',
            'symbol' => 'nullable|required',
        ]);
        try{
            DB::beginTransaction();
            $com = Currency::updateOrCreate(['id' => $this->getCurrencyRequest($request)['id']],$this->getCurrencyRequest($request));

            DB::commit();
            $res = [
                'status' => 1,
                'message'=> $com->wasRecentlyCreated?'Create Currency success':'Update Currency success',
                'data'   => $com,
            ];
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Create Currency not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }

    
    public function destroy($id)
    {
        DB::beginTransaction();
        try {

            $branch = Currency::find($id);
            $branch->delete();
            $res = [
                'status' => 1,
                'message'=> 'Deleted success',
                'data'   => $branch,
            ];
            DB::commit();
        }catch(Exception $e){
            DB::rollBack();
            $res = [
                'status'  => 0,
                'message' => 'Deleted not success',
                'data'    => $e->getMessage(),
            ];
        }
        return response()->json($res,200);
    }
    public function getCurrencyRequest($request)
    {
        $data = [
            'id'        => $request->id,
            'currency_en' => $request->currency_en,
            'currency_km' => $request->currency_km,
            'symbol' => $request->symbol,
        ];
        return $data;
    }

    public function admincurrency(Request $request)
    {
        $currency = Currency::orderBy('id', 'DESC')->get();
        return view('admin-system.currency.currency', compact('currency'));
    }

    public function admincreate()
    {
        return view('admin-system.currency.create');
    }

    public function adminedit($id)
    {
        $currency = Currency::findOrFail($id);
        return view('admin-system.currency.edit', compact('currency'));
    }

    public function adminstore(Request $request)
    {
        // dd($request->all());
        $request->validate([
            'currency_en' => 'required|string|max:255',
            'currency_km' => 'required|string|max:255',
            'symbol'      => 'required|string|max:10', 
        ]);

        try {
            DB::beginTransaction();
            Currency::create($request->only('currency_en', 'currency_km', 'symbol'));
            DB::commit();
            return redirect('currency')->with('success', 'Currency created successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Currency creation failed: ' . $e->getMessage());
        }
    }



    public function currencyupdate(Request $request, $id)
    {
        $currency = Currency::findOrFail($id);

        $currency->update($request->only('currency_en', 'currency_km', 'symbol',));

        return redirect('currency')->with('success', 'Currency updated successfully.');
    }

    public function admindestroy($id)
    {
        Currency::findOrFail($id)->delete();

        return redirect('currency')->with('success', 'Currency deleted successfully.');
    }

}
