<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Http\Request;

use App\Models\UsersTablesPreference;
use App\Models\User;

use Carbon\Carbon;

class TablesPreferencesController extends Controller
{
    
    protected $website_id;
    
    public function __construct(){
        
        $this->website_id = config('constants.website_id');
        
    }
    
    public function tablePreference(Request $request){
        
        $user_id = auth()->user()->id;
        
        // check if permission to do
        if(empty($user_id)){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $validator = Validator::make($request->all(), [
            'table' => 'required',
            'data' => 'required'
        ]);
        
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $update_criteria = [];
        $update_criteria['user_id'] = $user_id;
        
            
        $table = $request->table;
        $data = $request->data;
            
        UsersTablesPreference::updateOrCreate(
            $update_criteria, 
            [
                "user_id" => $user_id,
                $table => $data
            ]
        );
        
        return response()->json(['message' => 'Added Successfully']);

    }
    
    public function getTablePreferences()
    {
        
        $user_id = auth()->user()->id;
        
        // check if permission to do
        if(empty($user_id)){
            return response()->json(config('constants.messages.permission_denied'), 400);
            exit();
        }
        
        $table_preferences = UsersTablesPreference::where(['user_id' => $user_id])->get();
        
        return response()->json(['message' => config('constants.messages.response_success'), 'data'=> ['tables_preferences' => $table_preferences] ]);
    }
    
}