<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\UserCards;

class CardDetailAPIController extends Controller
{
    public function listCardDetails(Request $request)
    {
        try{
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            $results = UserCards::where('user_id',$user_id)->get();
            return $this->sendResponse($results, 'User card retrieved successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function addUpdateUserCardDetail(Request $request)
    {
        try{

            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            $post = $request->all();
            $post['user_id'] = $user_id;

            if($post['id']){
                UserCards::where('id',$post['id'])->update($post);
            }else{
                UserCards::create($post);                
            }
            
            $results = UserCards::where('user_id',$user_id)->get();
            return $this->sendResponse($results, 'User card saved successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function deleteUserCard($id,Request $request)
    {
        try{
            
            UserCards::where('id',$id)->delete();
            return $this->sendResponse([], 'User card deleted successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }

    public function setDefaultUserCard($id,Request $request)
    {
        try{
            $user_id = 0;            
            if($request->userAuthData){
                $user_id = $request->userAuthData->user_id;
            }
            $post = $request->all();
            $results = UserCards::where('user_id',$user_id)->update(array('set_as_default'=>$post['set_as_default']));
            UserCards::where('id',$id)->update(array('set_as_default'=>1));
            
            return $this->sendResponse([], 'User card updated successfully');
        } catch (RepositoryException $e) {
            return $this->sendError($e->getMessage());
        }
    }
}
