<?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, $checkoutID, $taxPercentage, $profitPercentage0_20, $profitPercentage20_50, $profitPercentage50_100, $profitPercentage100_200, $profitPercentage200_800, $profitPercentageMoreThan800, $priceCalculation)
    {
    	$this->dbh = $this->connectPDO1();
		$this->dbh->beginTransaction();
	    try
	    {
	    	$data['cl_user_id'] = 0;
	        $checkoutItem = $this->insert1($this->dbh, 'tb_checkout_item', $data);
	        if(!$checkoutItem)
	        {
	        	return 0;
	        	exit;
	        }

	        if($priceCalculation == 'Automatic')
	        {

		        $total = 0;
	      		$pvn = 0;
		        $items = $this->getAllItems($checkoutID);
		        if(!empty($items))
		        {
		        	foreach($items AS $item)
		        	{
		        		$where3['cl_id'] = $item['cl_product_id'];
		        		$product = $this->fetchRow('tb_product', $where3);
		        		
				         $salePrice = $item['cl_amount'];
				       

				        $total+= $salePrice;
				        if($pvn < $product['cl_shipping_price'])
				        {
				          $pvn = $product['cl_shipping_price'];
				        }
		        	}

		        	
		        }

		        $product = $this->getProduct($data['cl_product_id']);

		          if($product['cl_supplier_price'] < 20)
                {
                    $profitPercentage = $profitPercentage0_20;
                }
                else if($product['cl_supplier_price'] >= 20 && $product['cl_supplier_price'] <= 50)
                {
                    $profitPercentage = $profitPercentage20_50;
                }
                else if($product['cl_supplier_price'] >= 50 && $product['cl_supplier_price'] <= 100)
                {
                    $profitPercentage = $profitPercentage50_100;
                }
                else if($product['cl_supplier_price'] >= 100 && $product['cl_supplier_price'] <= 200)
                {
                    $profitPercentage = $profitPercentage100_200;
                }
		        else if($product['cl_supplier_price'] >= 200 && $product['cl_supplier_price'] <= 800)
		        {
		          $profitPercentage = $profitPercentage200_800;
		        }
		        else
		        {
		          $profitPercentage = $profitPercentageMoreThan800;
		        }

		         $salePrice = $product['cl_supplier_price'] + ($product['cl_supplier_price'] * $profitPercentage / 100);

		        $total+= $salePrice * $data['cl_quantity'];
		        if($pvn < $product['cl_shipping_price'])
		        {
		          $pvn = $product['cl_shipping_price'];
		        }

		        $data4['cl_pvn'] = $pvn + ($pvn * $taxPercentage/100);
				$data4['cl_total'] = $total + $data4['cl_pvn'];
	      		$data4['cl_total'] = $data4['cl_total'] + ($data4['cl_total'] * $taxPercentage/100);

	      	
		        $checkout = $this->update1('tb_checkout', $data4, ['cl_id' => $checkoutID] );
		        if(!$checkout)
		        {
		        	return 0;
		        	exit;
		        }
	        }
	        
	        $this->dbh->commit();
	        return 1;
	    }
	    catch (PDOException $e) {
	        // roll back transaction
	        $this->dbh->rollback();
	        return 0;
	    }
    }

    public function getProduct($id)
    {
    	return $this->fetchRow('tb_product', ['cl_id' => $id]);
    }

    public function getCheckout($id)
    {
    	return $this->fetchRow('tb_checkout', ['cl_id' => $id]);
    }

    public function getAllItems($id)
    {
    	return $this->fetchAll('tb_checkout_item', ['cl_checkout_id' => $id]);
    }

}


$obj = new addAjax();
if(!isset($_POST['data']) || !isset($_GET['id']) || !is_numeric($_GET['id']))
{
	http_response_code(400);
	echo json_encode(array('No input found'));
	exit;
}

$id = trim($_GET['id']);
$checkout = $obj->getCheckout($id);
if(!$checkout)
{
	http_response_code(400);
	echo json_encode(array('Checkout Not Found'));
	exit;
}

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



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

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

$integerFields = array('product_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;
}

$product = $obj->getProduct($data['product_id']);
if(!$product)
{
	http_response_code(404);
	echo json_encode(array('error_text' => 'Product Not Found'));
	exit;
}


   if($product['cl_supplier_price'] < 20)
    {
        $profitPercentage = $profitPercentage0_20;
    }
    else if($product['cl_supplier_price'] >= 20 && $product['cl_supplier_price'] <= 50)
    {
        $profitPercentage = $profitPercentage20_50;
    }
    else if($product['cl_supplier_price'] >= 50 && $product['cl_supplier_price'] <= 100)
    {
        $profitPercentage = $profitPercentage50_100;
    }
    else if($product['cl_supplier_price'] >= 100 && $product['cl_supplier_price'] <= 200)
    {
        $profitPercentage = $profitPercentage100_200;
    }
else if($product['cl_supplier_price'] >= 200 && $product['cl_supplier_price'] <= 800)
{
  $profitPercentage = $profitPercentage200_800;
}
else
{
  $profitPercentage = $profitPercentageMoreThan800;
}

$salePrice = $product['cl_supplier_price'] + ($product['cl_supplier_price'] * $profitPercentage / 100);


$data['amount'] = $salePrice * $data['quantity'];

//$data2['cl_total'] = $data['amount'] + $checkout['cl_total'] ;
//$where2['cl_checkout_id'] = $id;


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

$productID = $obj->index($data, $id, $taxPercentage, $profitPercentage0_20, $profitPercentage20_50, $profitPercentage50_100, $profitPercentage100_200, $profitPercentage200_800, $profitPercentageMoreThan800, $checkout['cl_price_calculation']);
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;