<?php
include_once "../../../config.php";
include_once "../../database1.php";
include_once "../../../validation.php";
include_once "../../../Helper.php";

require_once '../check_edit_page_ajax.php';

class updateFilter extends database{
	public function index($data, $id)
	{
		$where['cl_filter_id'] = $id;
		$where['cl_product_id'] = $data['cl_product_id'];

		$productFilter = $this->fetchRow('tb_product_filter', $where);
		if(!$productFilter)
		{
			return $this->insert('tb_product_filter', $data);
		}
		else
		{
			unset($data['cl_filter_id']);
			unset($data['cl_product_id']);
			return $this->update('tb_product_filter', $data,$where);
		}
	}

	
}

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();



$res = array();
$requiredFields = array('filter_id', 'value_id', 'product_id');
$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','cl_deleted_at');
$data = $validation->unsetValues($unsetFields, $data);
$data = $validation->setColumnPrefix($data);

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

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

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