<?php
require_once '_master/apiHandler.php';
require_once '_helper/store.php';

class pageClass extends apiHandler
{
    public function __construct()
    {
        parent::__construct();
        $this->checkERPAccess();
        //if($this->accessToken){
            $checkTokenClient = $this->checkTokenClient();
            $this->getrequest->clientid = isset($checkTokenClient->clientid) ? (int)$checkTokenClient->clientid : 0;
        //}
    }

    /**
     * Validate cart before checkout -- Check cart items availability 
     */
    function validate()
    {
        try {
            $clientId = $this->getrequest->clientid;

            // Find the client's current active offer (cart)
            $offerData = R::findOne('sellbilloffer', 'conditions=0 and orderSavedBillId=0 and sellbillclientid= ? order by sellbillid desc limit 1', [$clientId]);

            if (!$offerData) {
                $this->respond(404, false, $this->trans['messages']['cart']['notFound'], null, ['clientId' => $this->trans['messages']['cart']['notFound']]);
            }

            $cartItems = R::find('sellbilldetailoffer', 'sellbillid = ?', [$offerData['sellbillid']]);
            $storeId = $offerData['sellbillstoreid'];

            if (empty($cartItems)) {
                $this->respond(400, false, $this->trans['messages']['cart']['empty'], null, []);
            }

            $unavailableItems = [];

            foreach ($cartItems as $item) {
                list($storeDetailData, $storeDetailId, $productQuantityBefore) = storeHelper::getStoreDetails($storeId, $item['sellbilldetailproductid'], 0, 0, $item['sizeid'], $item['colorid']);

                $productNumber = R::getCell('SELECT productnumber FROM productunit where productunitid = ' . $item['productunitid']);
                if ($productQuantityBefore < $item['sellbilldetailquantity'] * $productNumber) {
                    $unavailableItems[] = [
                        'productId' => $item['sellbilldetailproductid'],
                        'sizeId' => $item['sizeid'],
                        'colorId' => $item['colorid'],
                        'requested' => $item['sellbilldetailquantity'],
                        'available' => $productQuantityBefore
                    ];
                }
            }

            if (!empty($unavailableItems)) {
                $this->respond(409, false, $this->trans['messages']['cart']['itemsUnavailable'], null, ['unavailableItems' => $unavailableItems], ['status' => 'invalid']);
            }

            // All items are available. Proceed with order creation or other logic.
            $this->respond(200, true, $this->trans['messages']['cart']['checkoutSuccess'], null, [], ['status' => 'valid']);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function calculate()
    {
        try {
            $allowed = ['address_id', 'coupon_code'];
            $fields = [
                'address_id' => ['rules' => 'required|integer|min:1', 'type' => 'integer'],
                'coupon_code' => ['rules' => 'text', 'type' => 'string']
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            $clientId = $this->getrequest->clientid;
            $addressId = $request['address_id'];
            $couponCode = $request['coupon_code'];

            // Get Cart/Offer Data
            $offerData = R::findOne('sellbilloffer', 'conditions=0 AND orderSavedBillId=0 AND sellbillclientid= ? ORDER BY sellbillid DESC LIMIT 1', [$clientId]);
            if (!$offerData) {
                $this->respond(404, false, $this->trans['messages']['cart']['notFound']);
            }

            $subtotal = (float)$offerData['sellbilltotalbill'];
            $itemsCount = (int)R::count('sellbilldetailoffer', 'sellbillid = ?', [$offerData['sellbillid']]);

            // Calculate Shipping
            $settings = R::load('onlinestoremainsetting', 1);
            if (!$settings) {
                $this->respond(500, false, 'Online store settings not found.');
            }

            $clientarea = R::findOne('clientarea', 'id = ?', [$addressId]);
            $default_shipping_cost = $clientarea ? $clientarea->shipping_cost : 0;

            $shippingCost = $default_shipping_cost;

            // Check for free shipping conditions
            if ($settings->shippingfree_numberitems == 1 && $itemsCount >= $settings->numberitems) {
                $shippingCost = 0;
            } elseif ($settings->shippingfree_totleitems == 1 && $subtotal >= $settings->totleitems) {
                $shippingCost = 0;
            }
            // If not free, check for fixed shipping cost
            elseif ($settings->fixedshipping_value == 1) {
                $shippingCost = $settings->shipping_value;
            }

            // Calculate Coupon Discount
            $couponDiscount = 0;
            if (!empty($couponCode)) {
                $coupon = R::findOne('coupons', 'code = ? AND is_active = 1', [$couponCode]);
                if ($coupon) {
                    $now = new DateTime();
                    $startDate = new DateTime($coupon->start_date);
                    $endDate = new DateTime($coupon->end_date);
                    if ($now >= $startDate && $now <= $endDate && $subtotal >= $coupon->minimum_order_value) {
                        if ($coupon->discount_type == 2) { // Fixed
                            $couponDiscount = (float)$coupon->discount_value;
                        } else if ($coupon->discount_type == 1) { // Percentage
                            $couponDiscount = ($subtotal * (float)$coupon->discount_value) / 100;
                        }
                    }
                }
            }

            //discount
            $discount = 0;
            $cartItems = R::find('sellbilldetailoffer', 'sellbillid = ?', [$offerData['sellbillid']]);
            if (!empty($cartItems)) {
                foreach ($cartItems as $item) {
                    $productNumber = R::getCell('SELECT productnumber FROM productunit where productunitid = ' . $item['productunitid']);
                    $productData = R::getRow('select discountType,productSellUnitPrice,priceAfterDiscount from product where productId = ' . $item['sellbilldetailproductid']);
                    if ($productData['discountType'] == 0) { //category discount

                        $categoryDiscount = R::getRow('select discounttype,selldiscount from productcat where productCatId = ' . $item['sellbilldetailcatid']);
                        if ($categoryDiscount['selldiscount'] > 0 && $categoryDiscount['discounttype'] == 0) { //direct
                            $discount += $categoryDiscount['selldiscount'] * $item['sellbilldetailquantity'] * $productNumber;
                        } else if ($categoryDiscount['selldiscount'] > 0 && $categoryDiscount['discounttype'] == 1) { //percentage
                            $discount += (($categoryDiscount['selldiscount'] / 100) * $item['sellbilldetailprice']) * $item['sellbilldetailquantity'] * $productNumber;
                        }
                    } elseif ($productData['discountType'] == 1) { //product discount
                        $discount += ($productData['productSellUnitPrice'] - $productData['priceAfterDiscount']) * $item['sellbilldetailquantity'] * $productNumber;
                    }
                }
            }

            $total = $subtotal + $shippingCost - $couponDiscount - $discount;

            $response = [
                'subtotal' => $subtotal,
                'discount' => $discount,
                'shipping_cost' => $shippingCost,
                'coupon_discount' => $couponDiscount,
                'total' => $total > 0 ? $total : 0
            ];

            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function placeOrder()
    {
        try {
            $allowed = ['address_id', 'coupon_code', 'payment_type', 'payment_details'];
            $fields = [
                'address_id' => ['rules' => 'required|integer|min:1', 'type' => 'integer'],
                'coupon_code' => ['rules' => 'text', 'type' => 'string'],
                'payment_type' => ['rules' => 'text', 'type' => 'string'],
                'payment_details' => ['rules' => 'text', 'type' => 'string']
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            $clientId = $this->getrequest->clientid;
            $addressId = $request['address_id']; // clientaddresses table
            $couponCode = $request['coupon_code'];
            $paymentTypeId = $request['payment_type_id']; // paymentmethods table
            $paymentDetails = $request['payment_details']; // not used for now
            $coupon =  (object)R::getRow('select * from coupons where code = ? and is_active = 1', [$couponCode]);
            $couponId = $coupon->id;
            if ($coupon) {
                $coupon_discount = $coupon->discount_value;
                if ($coupon->discount_type == 1) { // %
                    $coupon_discount = ($coupon->discount_value / 100) * $billValue;
                }
            }

            //sellbillpayed 
            $offerId = (int) R::getCell('SELECT sellbillid FROM sellbilloffer
                WHERE conditions=0 and orderSavedBillId=0 and sellbillclientid= ' . $clientId . ' order by sellbillid desc limit 1');
            $_GET['offerId'] = $offerId;
            R::exec('update sellbilloffer set addressid = ' . $addressId . ', couponid = ' . $couponId . ', paymenttypeid = ' . $paymentTypeId . ', paymentdetails = "' . $paymentDetails . '",sellbillaftertotalbill = sellbillaftertotalbill - ' . $coupon_discount . ' where sellbillid = ' . $offerId);

            $_POST['addressid'] = $addressId;
            $_POST['couponid'] = $couponId;
            $_POST['paymenttypeid'] = $paymentTypeId;
            $_POST['paymentdetails'] = $paymentDetails;
            //
            $_GET["do"] = "saveOfferAsBill";
            $control = "sellbillController.php";
            $jsonresponse = $this->CURL_WEB($control);
            $data = json_decode($jsonresponse, true);
            $sellbillId = isset($data['data']['id']) ? $data['data']['id'] : null;
            $billData = R::getRow('select sellbillaftertotalbill,sellbilldate from sellbill where sellbillid = ' . $sellbillId);

            if ($sellbillId) {
                $response = array(
                    "id" => $sellbillId,
                    "order_no" => $offerId,
                    "total" => $billData['sellbillaftertotalbill'],
                    "status" => "ordered",
                    "tracking_no" => "",
                    "created_at" => $billData['sellbilldate']
                );
                $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            } else {
                $this->respond(500, false, $this->trans['httpStatusCodes']['500'], ['raw_response' => $jsonresponse], []);
            }
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function CURL_WEB($control)
    {
        ##preparing url
        //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
        $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $control;
        $i = 0;
        foreach ($_GET as $key => $value) {
            if ($i == 0) {
                $url .= "?$key=$value";
            } else {
                $url .= "&$key=$value";
            }
            $i++;
        }


        $data_arr = array();
        ##preparing req. session
        $_POST['curlpost'] = 1;
        //set them static may change later

        require_once('../../models/sql/ConnectionProperty.class.php');
        $_SESSION['dbname'] = ConnectionProperty::getDatabase(); //"erp";
        $_SESSION['lic_dateto'] = date('Y-m-d');
        //
        $_SESSION['attempt'] = 0;
        $_SESSION['hidecat'] = 1;
        $_SESSION['clientnegative'] = 1;
        $_SESSION['suplliernegative'] = 1;
        $_SESSION['storenegative'] = 1;


        $_SESSION['userid'] = 1;
        $_SESSION['usergroupid'] = 1;
        $_SESSION['username'] = "admin";
        $_SESSION['usergroupname'] = "admin";
        $_SESSION['saveid'] = 1;
        $_SESSION['employeename'] = "admin";
        $_SESSION['searchinonesave'] = 0;
        $_SESSION['branchId'] = 1;
        $_SESSION['erp_lang'] = $lang = isset($allheaders["lang"]) ? $allheaders["lang"] : 'ar';
        $data_arr['sessionlist'] = json_encode($_SESSION);
        ##appending data
        foreach ($_POST as $key => $value) {
            $data_arr[$key] = $value;
        }

        ## start sending
        $post = $data_arr;
        $ch = curl_init($url);
        //
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Set to false
        //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
        //setting them to false.
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
        // execute!
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $location = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
        if ($http_code == 301 || $http_code == 302 || $http_code == 307 || $http_code == 308) {
            if ($location) {
                curl_close($ch);
                $ch = curl_init($location);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
                //setting them to false.
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
            }
        }
        if ($response === false) {
            //echo 'Error : ' . curl_error($ch);
        }

        // close the connection, release resources used
        curl_close($ch);
        // do anything you want with your response
        //var_dump($response);
        //print_r($response);
        return $response;
    }
}

require_once("_master/fireApi.php");
