<?php
$classMap['STORES'] = 'DB_STORES';
$classMap['PRODUCTS'] = 'DB_PRODUCTS';
$classMap['PRODUCTS_TRANSACTIONS'] = 'DB_PRODUCTS_TRANSACTIONS';
$classMap['POS_TRANSACTIONS'] = 'DB_POS_TRANSACTIONS';
$classMap['PRODUCTS_TRANSACTIONS_SESSIONS'] = 'DB_PRODUCTS_TRANSACTIONS_SESSIONS';
$classMap['PRODUCTS_HISTORY'] = 'DB_PRODUCTSHISTORY';
$classMap['CART'] = 'DB_CART';
$classMap['SUPPLIERS'] = 'DB_SUPPLIERS';
$classMap['SUPPLIERS'] = 'DB_SUPPLIERS';

class DB_CART extends DB_USERS
{
    private function USERS()
    {
        return new DB_USERS();
    }

    public function __construct()
    {
        parent::__construct();

    }
    function getCartContents($uidorhashkey)
    {
        if (!$uidorhashkey) {
            return false;
        }
        $DB = $this->DB;
        $wherearray = [];
        if (is_numeric($uidorhashkey)) {
            $wherearray = ['uid' => $uidorhashkey];
        } else {
            $wherearray = ['hashkey' => $uidorhashkey];
        }

        $DBQUERY = $this->USERS()->GetUserDatabyUID($uidorhashkey);
        if (!$DBQUERY) {
            return false;
        }

        $result = tryjsondecode($DBQUERY['cart']) ?? [];
        return $result;
    }
    function getCartContentsAndComputations($uidorhashkey){
        $cartContents= $this->getCartContents($uidorhashkey);
        if (!$cartContents){return false;}
        return $this->getCartDetailsComputations($cartContents);
    }
    function getCartDetailsComputations($cartdata)
    {
        if (!$cartdata || !is_array($cartdata)) {
            return false;
        }
        $productsClass = new DB_PRODUCTS_QUICK_MULTIPLESEARCH;
        $storeClass = new DB_STORES_QUICK_MULTIPLESEARCH;
        $CartDetails = [];
        $cartproducts = [];

       
        

        foreach ($cartdata as $value) {

            $cart_product_hashkey = $value['hashkey'] ?? $value[0];
            $cart_product_quantity = $value['quantity'] ?? $value[1];
            $cart_product_added = $value['added'] ?? $value[2];
            $cart_product_modified = $value['modified'] ?? $value[3];

            $productdata = $productsClass->getDetailsbyUIDorHashkey($cart_product_hashkey) ?? false;
            if (!$productdata) {
                continue;
            }

            
            $product_active = $productdata['status'] === 'active';
            $product_available = $productdata['available'] >= $cart_product_quantity;

            $productstore_uid = $productdata['storeuid'];

            $productstore_hash = $storeClass->getHASHfromUID($productstore_uid);

            $productphoto_array = tryjsondecode($productdata['photourl']);
            if (!is_array($productphoto_array)) {
                $productphotoarray = [];
            }
            $productphotourl = $productphoto_array[0] ?? null;

            $productprice = $productdata['price'];
            $product_unit = $productdata['unitname'];
            $product_name = $productdata['name'];
            if ($cart_product_quantity < 1) {
                return false;
            }

          
            $cartproducts[] = [
                'hashkey' => $cart_product_hashkey,
                'quantity' => $cart_product_quantity,
                'price' => $productprice,
                'unit' => $product_unit,
                'name' => $product_name,
                'photourl' => $productphotourl,
                'added' => $cart_product_added,
                'modified' => $cart_product_modified,
                'store' => $productstore_hash,
                'active' => $product_active,
                'available' => $product_available,
                'subtotal' => $productprice * $cart_product_quantity
            ];
        }

        $total = array_sum(array_column($cartproducts, 'subtotal'));
        if ($total < 2) {
            return false;
        }
        $CartDetails['details'] = [
            'total' => $total,
            'shipping' => 'Unknown'
        ];
        $CartDetails['cart'] = $cartproducts;

        return $CartDetails;
    }
    function SetCartContents($uidorhashkey, $newcontentsArray)
    {
        if (!$uidorhashkey) {
            return false;
        }
        $DB = $this->DB;
        $newcontentsArray = tryjsonencode($newcontentsArray);
        $newcontentsArray = ['cart' => $newcontentsArray];
        $DBNow = DBQUERY()->USERS()->ModifyUser($newcontentsArray, $uidorhashkey);
        return $DBNow;
    }
    function AddCartContentsSingleProduct($uidorhashkey, $producthashkey, $additionalquantity)
    {
        if (!$uidorhashkey) {
            return false;
        }
        $exists = DBQUERY()->USERS()->GetUserDatabyUID($uidorhashkey);
        if (!$exists) {
            return false;
        }
        if (!$producthashkey || is_numeric($producthashkey)) {
            return false;
        }

        if (!$additionalquantity || !is_numeric($additionalquantity)) {
            return false;
        }
        $contents = $this->getCartContents($uidorhashkey);
        if ($contents) {
            $producthashkeys = array_column($contents, 0);
        } else {
            $contents = [];
            $producthashkeys = [];
        }

        $targetkey = array_search($producthashkey, $producthashkeys);
        if ($targetkey === false) {
            $contents[] = [$producthashkey, $additionalquantity, serverdatetimesql(), serverdatetimesql()];
        } else {
            $content_details = $contents[$targetkey];
            $currentquantity = $content_details[1];
            $currentdate_added = $content_details[2];
            $newdate_modfied = serverdatetimesql();
            $newquantity = $currentquantity + $additionalquantity;
            if ($newquantity < 0) {
                return false;
            }
            $contents[$targetkey] = [$producthashkey, $newquantity, $currentdate_added, $newdate_modfied];
        }

        return $this->SetCartContents($uidorhashkey, $contents);
    }

    function EmptyCartContents($uidorhashkey)
    {
        if (!$uidorhashkey) {
            return false;
        }
        return $this->SetCartContents($uidorhashkey, []);
    }
    function DeleteCartContents($uidorhashkey, $producthashkey)
    {
        if (!$uidorhashkey) {
            return false;
        }
        if (!$producthashkey || is_numeric($producthashkey)) {
            return false;
        }
        $contents = $this->getCartContents($uidorhashkey);
        $producthashkeys = array_column($contents, 0);
        $targetkey = array_search($producthashkey, $producthashkeys);
        if ($targetkey === false) {
            unset($contents[$targetkey]);
            $contents = array_values($contents);
        }
        return $this->SetCartContents($uidorhashkey, $contents);
    }

    function CheckifProductisAllowedtoAddtoCart($producthashkeyoruid, $quantity)
    {
        //returns the product details if allowed, false if not
        $ProductDetails = DB_PRODUCTS()->getDetailsbyUIDorHashkey($producthashkeyoruid);
        if (!$ProductDetails || $ProductDetails['status'] !== 'active' || $ProductDetails['available'] < 1) {
            return false;
        }
        if ($quantity > $ProductDetails['available']) {
            return false;
        }
        return $ProductDetails;

    }
    function SetProductQuantityCartContent($uidorhashkey, $producthashkeyoruid, $quantity)
    {
        if (!$uidorhashkey || !$producthashkeyoruid || $quantity === null) {
            return false;
        }
        $producthashkeyifAllowed = $this->CheckifProductisAllowedtoAddtoCart($producthashkeyoruid, $quantity)['hashkey'] ?? false;
        if (!$producthashkeyifAllowed) {
            return false;
        }
        $producthashkeyoruid = $producthashkeyifAllowed;
        $contents = $this->getCartContents($uidorhashkey);
        if (!$contents) {
            $contents = [];
        }

        $producthashcolumns = array_column($contents, 0);

        $targetkey = array_search($producthashkeyoruid, $producthashcolumns);

        if ($targetkey === false) {
            $contents[] = [$producthashkeyoruid, $quantity, serverdatetimesql(), serverdatetimesql()];
        } else {
            $content_details = $contents[$targetkey];
            $currentquantity = $content_details[1];
            $currentdate_added = $content_details[2];
            $newdate_modfied = serverdatetimesql();
            $contents[$targetkey] = [$producthashkeyoruid, $quantity, $currentdate_added, $newdate_modfied];
        }


        $updatecontent = $this->SetCartContents($uidorhashkey, $contents);
        return $updatecontent;

    }
    function ShowCartStructure()
    {
        $structure = ['contenthashkey', 'quantity', 'date_added', 'date_modified'];
        e($structure);
    }

}



function CartDB($DB = false)
{
    return new DB_CART($DB);
}




class MARKET_MAIN
{
    public $DB = false;

    public function __construct($DB = false)
    {


    }
    function isNewTransactionAllowed($createdby_details, $createdfor_details, $ownerdetails)
    {

        if (!$createdby_details || !$createdfor_details || !$ownerdetails) {
            return false;
        }

        $parentflagAllowed = false;
        $acct_typeflagAllowed = false;

        $ownerUID = $ownerdetails['uid'] ?? false;
        if (!$ownerUID) {
            return false;
        }

        if (!is_array($createdby_details)) {
            $createdby_type = $createdby_details;
        } else {
            $createdby_type = $createdby_details['acct_type'];
        }

        if (!is_array($createdby_details)) {
            $createdfor_type = $createdfor_details;
        } else {
            $createdfor_type = $createdfor_details['acct_type'];
        }

        $createdby_Allowed_Types = $createdby_type === 'storeowner' || $createdby_type === 'storemanager' || $createdby_type === 'ult' || $createdby_type === 'superoperator';
        $createdfor_Allowed_Types = $createdby_type === 'storeowner' || $createdby_type === 'storemanager';
        $iscreatedbyULT = $createdby_type === 'ult';

        $createdfor_Parent = $createdfor_details['parentuid'];
        $createdby_Parent = $createdby_details['parentuid'];



        if ($createdfor_Parent === $ownerUID) {
            $parentflagAllowed = true;
        }


        if ($createdby_Allowed_Types && $createdfor_Allowed_Types) {
            $acct_typeflagAllowed = true;
        }


        if ($iscreatedbyULT) {
            return true;
        }


        if ($acct_typeflagAllowed && $parentflagAllowed) {
            return true;
        } else {
            return false;
        }
    }
    function getCityFromAddress($address)
    {
        $citiesfile = file_get_contents('lib/cities.json');
        $cities = json_decode($citiesfile) ?? false;
        $cities = array_column($cities, 'name') ?? false;

        if (!$cities) {
            return false;
        }
        foreach ($cities as $city) {
            if (stripos($address, $city) !== false) {
                return $city;
            }
        }
        return null;
    }
}

function MARKET_MAIN()
{
    return new MARKET_MAIN();
}


require_once('MarketDB/products.db.php');
require_once('MarketDB/productshistory.db.php');
require_once('MarketDB/product_transactions.db.php');
require_once('MarketDB/product_transactions_sessions.db.php');
require_once('MarketDB/product_transactions_sessions.db.php');
require_once('MarketDB/pos_transactions.db.php');
require_once('MarketDB/pos_transactions_sessions.db.php');
require_once('MarketDB/stores.db.php');
require_once('MarketDB/suppliers.db.php');

?>