<?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)
	{
		$where['cl_filter_id'] = $data['cl_filter_id'];
		$where['cl_product_id'] = $data['cl_product_id'];
		$where['cl_value_id'] = $data['cl_value_id'];


		$this->dbh = $this->connectPDO1();
		$this->dbh->beginTransaction();
	    try
	    {
			
			$productAttributeValue = $this->fetchRow('tb_product_attributes_values', $where);
			if(!$productAttributeValue)
			{
				return $this->insert('tb_product_attributes_values', $data);
			}
			else
			{
				unset($data['cl_filter_id']);
				unset($data['cl_product_id']);
				unset($data['cl_value_id']);
				return $this->update('tb_product_attributes_values', $data,$where);
			}

			$this->dbh->commit();
      		return 1;
			exit;
		}
    	catch (PDOException $e) 
    	{
	        // roll back transaction
	        $this->dbh->rollback();
	        return 0;
    	}
	}

	
}

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', 'show');
$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);
if(!$res)
{
	http_response_code(401);
	echo json_encode(array('error_text' => 'Something Went Wrong'));
	exit;
}

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

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