<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Gift;
use Illuminate\Http\Request;
use App\Models\User;
use Carbon\Carbon;

class GiftController extends Controller
{


    public function index(){
        $pageTitle = 'Users Gifts';
        $gifts = Gift::with('user')->latest()->paginate(getPaginate());
        $emptyMessage = 'Data Not Found';
        return view('admin.gift.index', compact('pageTitle', 'gifts', 'emptyMessage'));
    }

    public function create(Request $request){

        $request->validate([
            'username'=> 'required|string|max:191',
            'currency'=> 'required|string',
            'amount'=> 'required|numeric|gt:0',
            'expired_date'=> 'required|string',
            'status'=> 'required|in:0,1',
        ]);

        $user = User::where('username', $request->username)->first();

        if(!$user) {
            $notify[] = ['error', 'Coupon failed created due to invalid username'];
            return redirect()->back()->withNotify($notify);
        }
        

        $expiredDate = Carbon::createFromFormat('Y-m-d', $request->expired_date);

        $gift = new Gift();
        $gift->user_id = $user->id;
        $gift->currency = $request->currency;
        $gift->amount = $request->amount;
        $gift->expired_date = $expiredDate;
        $gift->code = getNumber(16);
        $gift->status = $request->status;
        $gift->save();

        $notify[] = ['success', 'Gift created successfully'];
        return redirect()->back()->withNotify($notify);

    }

    public function edit(Request $request){
        
        $request->validate([
            'username'=> 'required|string|max:191',
            'currency'=> 'required|string',
            'amount'=> 'required|numeric',
            'expired_date'=> 'required|string',
            'status'=> 'required|in:0,1',
        ]);

        $user = User::where('username', $request->username)->first();

        if(!$user) {
            $notify[] = ['error', 'Gift failed created due to invalid username'];
            return redirect()->back()->withNotify($notify);
        }
        
        $expiredDate = Carbon::createFromFormat('Y-m-d', $request->expired_date);

        $findGift = Gift::find($request->id);
        $findGift->user_id = $user->id;
        $findGift->currency = $request->currency;
        $findGift->amount = $request->amount;
        $findGift->expired_date = $expiredDate;
        $findGift->status = $request->status;
        $findGift->save();

        $notify[] = ['success', 'Gift updated successfully'];
        return redirect()->back()->withNotify($notify);
    }

}
