<?php
require_once '_master/apiHandler.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;
        //}
    }

    function index()
    {
        try {
            $this->getrequest->status  = isset($this->getrequest->status) ? $this->getrequest->status : '';
            $this->getrequest->id = (!empty($this->getrequest->id)) ? (int) $this->getrequest->id : 0;
            $this->getrequest->page = (!empty($this->getrequest->page)) ? (int) $this->getrequest->page : 1;
            $this->getrequest->limit = (!empty($this->getrequest->limit)) ? (int) $this->getrequest->limit : 10;

            if ($this->getrequest->id > 0) {
                $rulesellbill_id = 'integer';
            } else {
                $rulesellbill_id = 'required|integer|min:1';
            }

            $allowed = ['page', 'limit', 'id', 'status'];
            $fields = [
                'page' => [
                    'rules' => 'integer|min:1',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'limit' => [
                    'rules' => 'integer|min:1|max:100',
                    'type'  => 'integer',
                    'default' => 10
                ],
                'status' => [
                    'rules' => 'string|in:new,prepare,shipped,deliver,refused',
                    'type'  => 'string',
                    'message' => 'Status must be one of: new, prepare, shipped, deliver, or refused'
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(401, false, $this->trans['httpStatusCodes']['401'], null, $request['validation_errors']);
            $src = $this->hosturl . '/upload/pages/';

            if ($request['id'] > 0) {
                $response = R::getRow("SELECT sellbill.sellbillid,sellbilldate,sellbilltotalbill,sellbilldiscount,sellbilldiscounttype,sellbillaftertotalbill,sellbilltotalpayed,addressid,couponid,paymenttypeid,paymentdetails
                                   FROM sellbill
                                   WHERE sellbill.conditions = 0 AND sellbill.sellbillid = ?", [$request['id']]);
                $sellbill = $response;
                if ($sellbill['sellbillid'] > 0) {
                    $itemsArr = [];
                    $items = R::getAll("SELECT sellbilldetail.*, product.productName,product.productNameE,product.logo 
                                    FROM sellbilldetail JOIN product ON product.productid = sellbilldetail.sellbilldetailproductid
                                    WHERE sellbilldetail.sellbillid = ? ", [$sellbill['sellbillid']]);
                    foreach ($items as $item) {
                        $itemsArr[] = [
                            'id' => $item['sellbilldetailid'],
                            'product' => [
                                'id' => $item['sellbilldetailproductid'],
                                'name_ar' => $item['productName'],
                                'name_en' => $item['productNameE'],
                                'images' => [($item['logo'] != '' && $item['logo'] != '.' ? $this->hosturl . "/views/default/images/product_image/" . $item['logo'] : '')],
                            ],
                            'quantity' => $item['sellbilldetailquantity'],
                            'price' => $item['sellbilldetailtotalprice'],
                            'discount' => $item['discountvalue'],
                        ];
                    }
                    $itemsCount = count($items);
                    $offerId = R::getCell("SELECT sellbillid FROM sellbilloffer WHERE orderSavedBillId = ? ", [$sellbill['sellbillid']]);
                    $firstStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id ASC LIMIT 1", [$sellbill['sellbillid']]);
                    $lastStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id DESC LIMIT 1", [$sellbill['sellbillid']]);
                    $discount = $sellbill['sellbilldiscount'];
                    if ($sellbill['sellbilldiscounttype'] == 2) {
                        $discount = ($sellbill['sellbilldiscount'] / 100) * $sellbill['parcode'];
                    }

                    $coupon = R::load("coupons", $sellbill['couponid']);
                    if ($coupon) {
                        $coupon_discount = $coupon->discount_value;
                        if ($coupon->discount_type == 1) { // %
                            $billValue = $sellbill['sellbilltotalbill'] - $discount;
                            $coupon_discount = ($coupon->discount_value / 100) * $billValue;
                        }
                    }
                    $addressData = R::getRow("SELECT clientaddresses.name, clientaddresses.mobile,
                        concat(government.governmentname, ' / ', clientarea.name, ' / ', clientaddresses.addressDetails) as full_address
                                FROM `clientaddresses`
                                left join government on government.governmetid = clientaddresses.governorateid
                                left join clientarea on clientarea.id = clientaddresses.cityid
                                WHERE clientaddresses.id = ?", [$sellbill['addressid']]);
                    ## details
                    $resultsArray[] = [
                        'id' => $sellbill['sellbillid'],
                        'order_no' => $offerId,
                        'order_date' => $sellbill['sellbilldate'],
                        'tracking_no' => $firstStatus['id'],
                        'items_count' => $itemsCount,
                        'subtotal' => $sellbill['sellbilltotalbill'],
                        'discount' => $discount,
                        'coupon_discount' => $coupon_discount,
                        'total' => $sellbill['sellbillaftertotalbill'],
                        'status' => $lastStatus['status'],
                        'payment_type' => R::getCell("SELECT name_ar FROM paymentmethods WHERE id = ?", [$sellbill['paymenttypeid']]), //name_en
                        'payment_status' => ($sellbill['sellbilltotalpayed'] == $sellbill['sellbillaftertotalbill'] ? 'paid' : 'pending'),
                        'address' => $addressData,
                        'items' => $itemsArr,
                        // 'address'=>["name"=> "Home Address",//name
                        //             "mobile"=>"+201234567890",//mobile
                        //             "owner_name"=>"Ahmed Mohamed",//????
                        //             "full_address"=>"123 Main Street, Maadi, Cairo"],
                    ];
                }


                $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $resultsArray);
            }

            $allStatusArr = array("new", "prepare", "shipped", "deliver", "refused");

            // حساب الإزاحة (Offset)
            $offset = ($request['page'] > 0 ? $request['page'] - 1 : 0) * $request['limit'];
            if ($request['status'] != '') {
                $sql = 'SELECT sellbill.sellbillid,sellbilldate,sellbilltotalbill,sellbilldiscount,sellbilldiscounttype,sellbillaftertotalbill,sellbilltotalpayed,addressid,couponid,paymenttypeid,paymentdetails,sellbillstatus.status,tax
                                   FROM sellbill JOIN sellbillstatus ON sellbillstatus.sellbillid = sellbill.sellbillid
                                   WHERE sellbill.conditions = 0 and sellbill.sellbillclientid = ? AND sellbillstatus.status = ? limit ? OFFSET ?';
                $results = R::getAll($sql, [$this->getrequest->clientid, $request['status'], $request['limit'], $offset]);

                $totalRecords = R::getCell("SELECT COUNT(*) FROM sellbill JOIN sellbillstatus ON sellbillstatus.sellbillid = sellbill.sellbillid
                                   WHERE sellbill.conditions = 0 and sellbill.sellbillclientid = ? AND sellbillstatus.status = ?", [$this->getrequest->clientid, $request['status']]);

                $resultsArray = [];
                foreach ($results as $sellbill) {
                    $itemsCount = R::getCell("SELECT COUNT(*) FROM sellbilldetail WHERE sellbilldetail.sellbillid = ? ", [$sellbill['sellbillid']]);
                    $offerId = R::getCell("SELECT sellbillid FROM sellbilloffer WHERE orderSavedBillId = ? ", [$sellbill['sellbillid']]);
                    $firstStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id ASC LIMIT 1", [$sellbill['sellbillid']]);
                    $lastStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id DESC LIMIT 1", [$sellbill['sellbillid']]);
                    $discount = $sellbill['sellbilldiscount'];
                    if ($sellbill['sellbilldiscounttype'] == 2) {
                        $discount = ($sellbill['sellbilldiscount'] / 100) * $sellbill['parcode'];
                    }
                    ## all user orders?
                    $resultsArray[] = [
                        'id' => $sellbill['sellbillid'],
                        'order_no' => $offerId,
                        'order_date' => $sellbill['sellbilldate'],
                        'tracking_no' => $firstStatus['id'],
                        'items_count' => $itemsCount,
                        'subtotal' => $sellbill['sellbilltotalbill'],
                        'discount' => $discount,
                        'total' => $sellbill['sellbillaftertotalbill'],
                        'status' => $lastStatus['status'],
                        'tax' => $sellbill['sellbilltotalbill'] * ($sellbill['tax'] / 100),
                        'payment_type' => R::getCell("SELECT name_ar FROM paymentmethods WHERE id = ?", [$sellbill['paymenttypeid']]), //name_en
                        'payment_status' => ($sellbill['sellbilltotalpayed'] == $sellbill['sellbillaftertotalbill'] ? 'paid' : 'pending'),
                    ];
                }
            } else {
                ## old get all orders with limit
                /*$sql = 'SELECT sellbill.sellbillid,sellbilldate,sellbilltotalbill,sellbilldiscount,sellbilldiscounttype,sellbillaftertotalbill,sellbilltotalpayed,addressid,couponid,paymenttypeid,paymentdetails,sellbillstatus.status,tax
                                   FROM sellbill JOIN sellbillstatus ON sellbillstatus.sellbillid = sellbill.sellbillid
                                   WHERE sellbill.conditions = 0 and sellbill.sellbillclientid = ? limit ? OFFSET ?';
                $results = R::getAll($sql, [$this->getrequest->clientid, $request['limit'], $offset]);

                $totalRecords = R::getCell("SELECT COUNT(*) FROM sellbill
                                   WHERE sellbill.conditions = 0 and sellbill.sellbillclientid = ? ", [$this->getrequest->clientid]);*/
                ## new get orders by status
                // foreach ($allStatusArr as $status) {
                    // Apply limit and offset only for 'deliver' and 'refused' statuses
                    $sql = 'SELECT sellbill.sellbillid,sellbilldate,sellbilltotalbill,sellbilldiscount,sellbilldiscounttype,sellbillaftertotalbill,sellbilltotalpayed,addressid,couponid,paymenttypeid,paymentdetails,sellbillstatus.status,tax
                                   FROM sellbill JOIN sellbillstatus ON sellbillstatus.sellbillid = sellbill.sellbillid
                            WHERE sellbill.conditions = 0 and sellbill.sellbillclientid = ? 
                            ORDER BY sellbill.sellbillid DESC LIMIT ? OFFSET ?';

                    $statusResults = R::getAll($sql, [$this->getrequest->clientid, $request['limit'], $offset]);

                    // Get total count for this status
                    $totalRecords = R::getCell("SELECT COUNT(*) FROM sellbill 
                                        JOIN sellbillstatus ON sellbillstatus.sellbillid = sellbill.sellbillid
                                        WHERE sellbill.conditions = 0 AND sellbill.sellbillclientid = ? ", [$this->getrequest->clientid]);
                    $resultsArray = [];
                    $resultsArray['orders'] = [];
                    foreach ($statusResults as $sellbill) {
                        $itemsCount = R::getCell("SELECT COUNT(*) FROM sellbilldetail WHERE sellbilldetail.sellbillid = ? ", [$sellbill['sellbillid']]);
                        $offerId = R::getCell("SELECT sellbillid FROM sellbilloffer WHERE orderSavedBillId = ? ", [$sellbill['sellbillid']]);
                        $firstStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id ASC LIMIT 1", [$sellbill['sellbillid']]);
                        $lastStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id DESC LIMIT 1", [$sellbill['sellbillid']]);
                        $discount = $sellbill['sellbilldiscount'];
                        if ($sellbill['sellbilldiscounttype'] == 2) {
                            $discount = ($sellbill['sellbilldiscount'] / 100) * $sellbill['parcode'];
                        }
                        ## all user orders?
                        $resultsArray['orders'][] = [
                            'id' => $sellbill['sellbillid'],
                            'order_no' => $offerId,
                            'order_date' => $sellbill['sellbilldate'],
                            'tracking_no' => $firstStatus['id'],
                            'items_count' => $itemsCount,
                            'subtotal' => $sellbill['sellbilltotalbill'],
                            'discount' => $discount,
                            'total' => $sellbill['sellbillaftertotalbill'],
                            'status' => $lastStatus['status'],
                            'tax' => $sellbill['sellbilltotalbill'] * ($sellbill['tax'] / 100),
                            'payment_type' => R::getCell("SELECT name_ar FROM paymentmethods WHERE id = ?", [$sellbill['paymenttypeid']]), //name_en
                            'payment_status' => ($sellbill['sellbilltotalpayed'] == $sellbill['sellbillaftertotalbill'] ? 'paid' : 'pending'),
                        ];
                    }
                    $resultsArray['pagination'] = [
                        "current_page" => (int) $request['page'],
                        "total_pages" => ceil($totalRecords / $request['limit']),
                        "total_items" => (int) $totalRecords,
                        "per_page" => $request['limit']
                    ];
                // }
            }


            if ($request['id'] > 0) {
                $response = $resultsArray;
            } else {
                if ($request['status'] != '') {
                    $response = array(
                        "orders"  => [$resultsArray],
                        "pagination" => [
                            "current_page" => (int) $request['page'],
                            "total_pages" => ceil($totalRecords / $request['limit']),
                            "total_items" => (int) $totalRecords,
                            "per_page" => $request['limit']
                        ]
                    );
                } else {
                    $response = $resultsArray;
                    
                }
            }
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }
    function track()
    {
        $this->getrequest->id = (!empty($this->getrequest->id)) ? (int) $this->getrequest->id : 0;
        $allowed = ['id'];
        $fields = [
            'id' => [
                'rules' => 'integer',
                'type'  => 'integer',
            ],
        ];
        $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
        if ($request['validation_errors']) $this->respond(401, false, $this->trans['httpStatusCodes']['401'], null, $request['validation_errors']);
        if ($request['id'] > 0) {
            $firstStatus = R::getRow("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id ASC LIMIT 1", [$request['id']]);
            $orderAllStatus = R::getAll("SELECT * FROM sellbillstatus WHERE sellbillid = ? ORDER BY id DESC", [$request['id']]);
            if (!$orderAllStatus) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, []);
            } else {
                $stArrTmp = array();
                foreach ($orderAllStatus as $lastStatus) {
                    $stArrTmp[] = [
                        'tracking_no' => $firstStatus['id'],
                        'status' => $lastStatus['status'],
                        'updated_at' => $lastStatus['sysdate']
                    ];
                }
                $deliveredRows = array_filter($stArrTmp, function ($item) {
                    return $item['status'] === 'deliver';
                });
                $response = array(
                    "data"  => ["deliverstatus" => $deliveredRows, 'statusArr' => $stArrTmp]
                );
                // $response = array(
                //     "data"  => [
                //         'order_no' => $this->getrequest->id,
                //         'tracking_no' => $lastStatus['id'],
                //         'status' => $lastStatus['status'],
                //         'updated_at' => $lastStatus['sysdate'],
                //     ]
                // );
            }
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        }
    }

    function reorder()
    {
        try {
            // Get order ID from request
            $clientId = $this->getrequest->clientid;

            if ($clientId <= 0) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], 'Client ID is required', []);
                return;
            }

            $lastCart_executedAsOrder_id = (int)R::getCell('select sellbillid from sellbilloffer where sellbillclientid = ? and orderSavedBillId > 0 and conditions = 0 order by orderSavedBillId desc limit 1', [$clientId]);
            if ($lastCart_executedAsOrder_id == 0) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], 'Order not found or empty', []);
                return;
            }
            // Fetch order details
            $orderDetails = R::getAll(
                'SELECT d.*, p.productName, p.productSellUnitPrice, p.discount
                 FROM sellbilldetailoffer d 
                 JOIN product p ON d.sellbilldetailproductid = p.productId 
                 WHERE d.sellbillid = ?',
                [$lastCart_executedAsOrder_id]
            );

            if (empty($orderDetails)) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], 'Order not found or empty', []);
                return;
            }

            // First, clear the current cart for this client
            $_POST = array();
            $_POST['id'] = $clientId;
            $this->CURL_WEB('api/cart.php/clear');

            $addedItems = [];
            $failedItems = [];

            // Add each product to cart
            $lastId = 0; //detailid of cart
            foreach ($orderDetails as $item) {
                // Prepare POST data
                $_POST = array();
                $_POST = [
                    'clientId' => $clientId,
                    'product_id' => isset($item['sellbilldetailproductid']) ? $item['sellbilldetailproductid'] : 0,
                    'size_id' => isset($item['sizeid']) ? $item['sizeid'] : 0,
                    'color_id' => isset($item['colorid']) ? $item['colorid'] : 0,
                    'quantity' => $item['sellbilldetailquantity'],
                    'price' => $item['productSellUnitPrice'], //sellbilldetailprice
                    'discount' => $item['discountvalue']
                ];
                // Call cart API to add item with POST data
                $result_json = $this->CURL_WEB('api/cart.php/items');
                $data = json_decode($result_json, true);
                $lastId = $data['body']['cart']['id'];

                if ($data['success'] && $lastId > 0) {
                    $addedItems[] = [
                        'product_id' => $item['sellbilldetailproductid'],
                        'name' => $item['productName'],
                        'quantity' => $item['sellbilldetailquantity'],
                        'price' => $item['productSellUnitPrice'], //sellbilldetailprice
                    ];
                } else {
                    $failedItems[] = [
                        'product_id' => $item['sellbilldetailproductid'],
                        'name' => $item['productName'],
                        'error' => isset($result['message']) ? $result['message'] : 'Failed to add to cart'
                    ];
                }
            }

            if ($lastId > 0) {
                $cartid = (int) R::getCell('select sellbillid from sellbilldetailoffer where sellbilldetailid = ?', [$lastId]);
                // Get updated cart summary
                $_POST = array();
                $_POST['id'] = $clientId;
                $cartSummary = $this->CURL_WEB('api/cart.php');

                // $response = [
                //     'success' => true,
                //     'message' => 'Order items added to cart',
                //     'cart_id' => $cartid,
                //     'added_items' => $addedItems,
                //     'failed_items' => $failedItems,
                //     'cart_summary' => $cartSummary
                // ];

                //$this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
                echo $cartSummary;
            } else {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], 'Failed to add to cart', []);
            }
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }
    function cancel()
    {
        try {

            $this->getrequest->id = (!empty($this->getrequest->id)) ? (int) $this->getrequest->id : 0;
            $allowed = ['id'];
            $fields = [
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
            ];
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(401, false, $this->trans['httpStatusCodes']['401'], null, $request['validation_errors']);
            $id = !empty($request['id']) ? (int)$request['id'] : 0;
            // Get order ID from request
            $clientId = $this->getrequest->clientid;



            if ($clientId <= 0) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], 'Client ID is required', []);
                return;
            }

            ###################
            $QueryString = '';
            if ($id > 0) {
                $QueryString = ' and sellbill.sellbillid = ' . $id;
            } else {
                $QueryString = ' and sellbillclientid = ' . $clientId;
            }
            // Get the sellbill ID from the offer table
            $sellbillId = R::getCell("SELECT sellbill.sellbillid 
                FROM sellbill 
                join sellbillstatus on sellbillstatus.sellbillid = sellbill.sellbillid
                WHERE conditions = 0 $QueryString and sellbilltotalpayed < sellbillaftertotalbill and sellbillstatus.status in ('new','prepare','shipped')");

            // Check if the order exists
            if (!$sellbillId) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], 'No Pending Order found', []);
                return;
            }



            //
            $_GET['sellbillid'] = $sellbillId;
            //
            $_GET["do"] = "delete";
            $control = "sellbillController.php";
            $jsonresponse = $this->CURL_WEB($control);
            $data = json_decode($jsonresponse, true);
            $flag = isset($data['status']) && $data['status'] == 1 ? 'success' : 'error';

            if ($flag == 'success') {
                // Update the sellbill status to 'refused'
                $status = R::dispense('sellbillstatus');
                $status->sellbillid = $sellbillId;
                $status->status = 'refused';
                $status->sysdate = date('Y-m-d H:i:s');
                $status->userid = 1; //$request['clientid'];
                R::store($status);

                // Return success response
                $response = [
                    'order_id' => $sellbillId,
                    'status' => 'cancelled',
                    'message' => 'Order has been cancelled successfully'
                ];

                $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            } else {
                $response = [
                    'order_id' => $sellbillId,
                    'message' => 'failed to cancel order'
                ];
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $response);
            }
        } catch (Exception $e) {
            // Rollback on error
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->getMessage(), []);
        }
    }


    function rating()
    {
        try {
            $allowed = ['id', 'rate', 'rating_text'];
            // Input validation rules
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'message' => 'Invalid Order ID'
                ],
                'rate' => [
                    'rules' => 'required|integer|min:0|max:5',
                    'message' => 'Rating must be between 0 and 5'
                ],
                'rating_text' => [
                    'rules' => 'max:1000',
                    'message' => 'Rating text is too long (max 1000 characters)'
                ]
            ];
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);

            // Validate input
            $id = !empty($request['id']) ? (int)$request['id'] : 0;
            $rate = !empty($request['rate']) ? (int)$request['rate'] : 0;
            $rating_text = !empty($request['rating_text']) ? $request['rating_text'] : '';

            // Get the sell bill
            $sellbill = R::getCell("SELECT sellbillid FROM sellbill WHERE sellbillid = ?", [$id]);

            if (empty($sellbill)) {
                throw new Exception('Order not found');
            }

            R::exec("UPDATE sellbill SET rating = ?, rating_text = ? WHERE sellbillid = ?", [$rate, $rating_text, $id]);

            $response = [
                'id' => $id,
                'rate' => $rate,
                'rating_text' => $rating_text
            ];
            // Return success response
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $e) {
            // Handle errors
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->getMessage(), []);
        }
    }


    function getrating()
    {
        try {
            $allowed = ['id'];
            // Input validation rules
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'message' => 'Invalid Order ID'
                ]
            ];

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

            $id = (int)$request['id'];

            // Get the rating and rating text
            $rating = R::getRow("SELECT rating as rate, rating_text FROM sellbill WHERE sellbillid = ?", [$id]);

            if (empty($rating)) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], 'Order not found', []);
                return;
            }

            $response = [
                'rate' => $rating['rate'],
                'rating_text' => $rating['rating_text']
            ];

            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $e) {
            // Handle errors
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->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);
        //

        ## this if i want to use another api controller headers will be needed
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getMainHeaderVars()); //// newwwwwwwwww

        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;
    }

    function getMainHeaderVars()
    {
        // Step 1: Get headers from the incoming request
        $headers = getallheaders();
        $openkey = isset($headers['openkey']) ? $headers['openkey'] : '';
        $lang = isset($headers['lang']) ? $headers['lang'] : 'ar';
        $accesstoken = isset($headers['accesstoken']) ? $headers['accesstoken'] : '';
        $useERPIDs = isset($headers['useERPIDs']) ? $headers['useERPIDs'] : 0;
        // Step 2: Prepare the header format for cURL
        $curlHeaders = [
            // "Authorization: Bearer " . $this->accessToken,
            // "Content-Type: application/json"
            "openkey: $openkey",
            "lang: $lang",
            "accesstoken: $accesstoken",
            "useERPIDs: $useERPIDs",
        ];
        return $curlHeaders;
    }

    public function __destruct()
    {
        parent::__destruct();
    }
}
require_once("_master/fireApi.php");
