<?php
session_start();
require_once "../../config.php";
require_once "../../../validation.php";
require_once "../../../Helper.php";
require_once '../../database1.php';
require_once "../../check_admin.php";

class addAjax extends database
{
   public function index($data)
    {
        return $this->insert('tb_product',$data);
    }

    public function checkSlug($slug)
    {
    	$where['cl_slug'] = $slug;
    	return $this->fetchRow('tb_product', $where);
    }
}


$obj = new addAjax();
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('name', 'slug', 'cat_id', 'sub_cat_id', 'supplier_price', 'profit_percentage', 'monthly_price', 'brand_id','meta_description','keywords', 'active');
$return = $validation->checkRequired($requiredFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

$numericFields = array('supplier_price', 'profit_percentage', 'monthly_price');
$return = $validation->checkNumeric($numericFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

$integerFields = array('cat_id', 'sub_cat_id', 'brand_id');
$return = $validation->checkInteger($integerFields, $data);
if($return)
{
	$res['error_description'][] = $return;
}

if(!empty($res['error_description']))
{
	$result['error_description'] = $validation->setErrors($res['error_description']);
	$result['error_text'] = $validation->setErrors($res['error_description']);

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

$slug = $obj->checkSlug($data['slug']);
if($slug)
{
	http_response_code(400);
	echo json_encode(array('error_text' => 'Slug Already exists'));
	exit;
}



$data = $validation->removeEmptyValues($data);

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

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

http_response_code(200);
echo json_encode(array('message' => 'Product Added Successfully', 'id' => $productID));
exit;