<?php
include_once "../../includes/config.php";
include_once "../../includes/database.php";
include_once "../../includes/validation.php";
include_once "../../includes/Helper.php";
include_once "../../includes/ajax/check_session_ajax.php";
require_once '../../includes/ajax/check_edit_page_ajax.php';
include_once "../../includes/auth.php";
$auth = array('customer_admin');
$authRes = checkAuth($auth, $user);
if(!$authRes)
{
    http_response_code(401);
	echo json_encode(array('error_text' => 'Authntication Error'));
	exit;
}

class AddAjax extends database{
    public function index($data, $id, $userID)
    {
        $where['cl_id'] = $id;
        $where['cl_user_id'] = $userID;
        return $this->update('tb_tables', $data, $where);
    }
        
    public function currentTable($id)
    {
        return $this->fetchRow('tb_tables', ['cl_id' => $id]);
    }
}

if(!isset($_POST['data']))
{
	http_response_code(400);
	echo json_encode(array('No input found'));
	exit;
}

$data = $_POST['data'];
$helper = new Helper();
$validation = new validation();

//$data = $helper->changeSerialzeArrayValues($data);

$res = array();
$requiredFields = array('table_name');
$return = $validation->checkRequired($requiredFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}



if(!empty($res['error_description']))
{
	$result['error_description'] = $validation->setErrors($res['error_description']);
	$result['error_text'] = 'Following errors occured while you were trying to submit data';

	http_response_code(400);
	echo json_encode($result);
	exit;
}


$unsetFields = array('id', 'deleted_at');
$data = $validation->unsetValues($unsetFields, $data);
$data = $validation->setColumnPrefix($data);

$obj = new AddAjax();

$table = $obj->currentTable($id);
if(!$table || $table['cl_user_id'] != $user['cl_id'])
{
    http_response_code(401);
    echo json_encode(array('error_text' => 'Something Went Wrong'));
    exit;
}


$res = $obj->index($data, $id, $user['cl_id']);
if(!$res)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

session_start();
$_SESSION['error_message'] = 'Updated Successfully';
$_SESSION['error_type'] = 'success';

http_response_code(200);
echo json_encode(array('message' => 'Updated Successfully'));
exit;