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

require_once '../../database1.php';
require_once "../../check_admin.php";

require_once '../check_edit_page_ajax.php';

class EditAjax extends database{
	public function deleteItem($id, $checkoutID, $taxPercentage)
	{
		$this->dbh = $this->connectPDO1();
		$this->dbh->beginTransaction();
	    try
	    {
			$where['cl_id'] = $id;
			$data['cl_deleted_at'] = date("Y-m-d H:i:s");
			$res = $this->update('tb_checkout_item', $data,$where);
			if(!$res)
			{
				return 0;
				exit;
			}

			$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'];
			        }
	        	}
	        }

	        $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 getAllItems($id)
	{
    	return $this->fetchAll('tb_checkout_item', ['cl_checkout_id' => $id]);
    }

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


$obj = new EditAjax();

$userOrderItem = $obj->getCurrentCheckoutItem($id);
if(!$userOrderItem)
{
	http_response_code(404);
	echo json_encode(array('error_text' => 'Checkout Item Not Found'));
	exit;
}

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

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

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