<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GiftCardAmount;
use App\Models\GiftCards;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class GiftCardController extends Controller
{
    public function index(){
        $search = request('search');
        $giftCard = GiftCards::with('giftCardAmount')->when($search, function($q) use($search){$q->where('card_name','like',"%$search%");})->paginate(16);

       // $cardAmounts = $giftCard->giftCardAmount;
      // dd($amounts);
        return view('admin.giftcard.index', compact('giftCard'));
    }

    public function store(Request $request){

        $request->validate([
            'card_name'=>'required|unique:gift_cards'
        ]);
        try{
            $giftCard = new GiftCards();
            $giftCard->card_name = $request->card_name;
            $giftCard->save();
            return back()->with('success','Operation Successful');
        }catch (\Throwable $th){
            return back()->with('error',$th->getMessage());
        }

    }

    public function createGiftcardAmount(Request $request){

        $request->validate([
            'gift_card'=>'required',
            'rate'=>'required|numeric',
            'amount'=>'required|numeric',
            'refer_bonus'=>'required|numeric',
            ]);

        try{

            $giftCardAmount = new GiftCardAmount();
            $giftCardAmount->card_id= $request->gift_card;
            $giftCardAmount->amount = $request->amount;
            $giftCardAmount->rate = $request->rate;
            $giftCardAmount->refer_bonus = $request->refer_bonus;
            $giftCardAmount->save();
            return back()->with('success','Giftcard Amount Added Successfully');
        }catch(\Throwable $th){
            return back()->with('error',$th->getMessage());
        }
    }
    public function editGiftcardAmount(Request $request){

        $request->validate([

            'rate'=>'required|numeric',
            'amount'=>'required|numeric',
            'refer_bonus'=>'required|numeric',

            ]);

        try{

            $giftCardAmount =  GiftCardAmount::where('id', $request->id)->firstOrFail();
            $giftCardAmount->amount = $request->amount;
            $giftCardAmount->rate = $request->rate;
            $giftCardAmount->refer_bonus = $request->refer_bonus;
            $giftCardAmount->save();
            return back()->with('success','Giftcard Amount Added Successfully');
        }catch(\Throwable $th){
            return back()->with('error',$th->getMessage());
        }
    }
}
