<?php


class DB_PRODUCTS
{

    public $DB = false;
    public $tablename = 'products';

    use BASICDB;
    public function __construct($DB = false)
    {
        if (!$DB) {
            $DB = DB();
        }
        if (!$DB) {
            return false;
        }
        if ($DB) {
            $this->DB = $DB;
        }
        if (!$this->tablename) {
            return false;
        }

    }

    function NewWholesaleProduct(
        $name,
        $description,
        $price,
        $unitname,
        $storeuid,
        $available = 0,
        $photourl = '',
        $barcode = '',
        $specs = '',
        $owneruid = '',
        $sold = '',
        $category = '',
        $subcategory = '',
        $remarks = '',
        $status = '',
        $sku = '',
        $shortcode = '',
        $shortname = '',
        $qrcode = '',
        $reviews = '',
        $createdby = '',
        $rating = '',
        $createdfor = ''
    ) {
        if (!$specs) {
            $specs = [];
        }
        $specs[]='wholesale';

        return $this->NewProduct($name,
        $description,
        $price,
        $unitname,
        $storeuid,
        $available,
        $photourl,
        $barcode,
        $specs,
        $owneruid ,
        $sold,
        $category,
        $subcategory,
        $remarks,
        $status,
        $sku,
        $shortcode,
        $shortname,
        $qrcode,
        $reviews,
        $createdby,
        $rating,
        $createdfor);

    }

    function NewProduct(
        $name,
        $description,
        $price,
        $unitname,
        $storeuid,
        $available = 0,
        $photourl = '',
        $barcode = '',
        $specs = '',
        $owneruid = '',
        $sold = '',
        $category = '',
        $subcategory = '',
        $remarks = '',
        $status = '',
        $sku = '',
        $shortcode = '',
        $shortname = '',
        $qrcode = '',
        $reviews = '',
        $createdby = '',
        $rating = '',
        $createdfor = ''
    ) {

        if (!$name || !$description || !$price || !$unitname || !$storeuid) {
            return false;
        }

        $storedata = DBQUERY()->STORES()->CheckifUIDorHashKeyExist($storeuid);

        if (!$storedata) {
            return false;
        }


        $data = [];
        $addtofinalDBVar = function ($varvalue, $varname, $tryjson = false) use (&$data) {
            if ($varvalue) {
                if ($tryjson and is_array($varvalue)) {
                    $varvalue = tryjsonencode($varvalue);
                }
                $data[$varname] = $varvalue;
            }

        };

        global $CurrentUserUID;

        if (!$createdby) {
            $createdby = $CurrentUserUID;
        }

        if (!$createdby) {
            $createdby = CurrentUserUID();
        }

        if (!$createdfor) {
            $createdfor = $createdby;
        }

        if (!$status) {
            $status = 'active';
        } else {
            $status = strtolower($status);
        }


        $ownerUIDCheckifParent = function ($owneruid, $createdfor, $createdby) {

            $createdby_isParentofOwner = DB_USERS()->isTargetUserAChildofParent($owneruid, $createdby);
            if ($createdby_isParentofOwner) {
                return true;
            }

            $createdfor_isParentofOwner = DB_USERS()->isTargetUserAChildofParent($owneruid, $createdfor);
            if ($createdfor_isParentofOwner) {
                return true;
            }

            $Owner_isParentofCreatedby = DB_USERS()->isTargetUserAChildofParent($createdby, $owneruid);
            if ($Owner_isParentofCreatedby) {
                return true;
            }
            return false;

        };


        $createdby_details = DB_USERS()->getDetailsbyUIDorHashkey($createdby);
        if (!$createdby_details) {
            return false;
        }
        if ($createdby !== $createdfor) {
            $createdfor_details = DB_USERS()->getDetailsbyUIDorHashkey($createdfor);
        } else {
            $createdfor_details = $createdby_details;
        }

        if (!$createdfor_details) {
            return false;
        }

        $createdby_type = $createdby_details['acct_type'];
        $createdby_uid = $createdby_details['uid'];
        $createdbyfor_type = $createdfor_details['acct_type'];
        $createdfor_uid = $createdfor_details['uid'];

        $storeuid_details = $storedata;
        if (!$storeuid) {
            return false;
        }
        $storeuid = $storeuid_details['uid'];

        $storeuid_owneruid = $storeuid_details['owneruid'];


        if (!$owneruid) {
            $owneruid = $storeuid_owneruid;
        }

        $createdby_is_StoreOwner = $createdby_type === 'storeowner';
        $createdby_is_StoreManager = $createdby_type === 'storemanager';
        $createdfor_is_StoreOwner = $createdbyfor_type === 'storeowner';
        $createdfor_is_StoreManger = $createdbyfor_type === 'storemanager';
        $createdby_is_Ult = $createdby_type === 'ult';
        $createdby_is_Operator = $createdby_type === 'operator';
        $createdby_is_Admin = $createdby_type === 'admincore';




        if (!$createdby_is_StoreManager && !$createdby_is_StoreOwner && !$createdfor_is_StoreOwner && !$createdfor_is_StoreManger && !$createdby_is_Ult && !$createdby_is_Operator && !$createdby_is_Admin) {
            return false;
        }




        if ($owneruid) {
            $owner_details = DBQUERY()->USERS()->getDetailsbyUIDorHashkey($owneruid);
            if (!$owner_details) {
                return false;
            }
        }

        if (!$ownerUIDCheckifParent($owneruid, $createdfor, $createdby)) {
            return false;
        }


        $createdby_is_SameUIDAsStoreOwner = $createdby_uid === $storeuid_owneruid;
        $createdfor_is_SameUIDAsStoreOwner = $createdfor_uid === $storeuid_owneruid;

        $isOwnerofStore = $createdby_is_SameUIDAsStoreOwner || $createdfor_is_SameUIDAsStoreOwner || $createdby_is_Ult;


        if (!$isOwnerofStore) {
            return false;
        }



        $userdata = DB_USERS()->GetUserDatabyUID($createdby, ['username', 'nickname']);
        if (!$userdata) {
            return false;
        }
        $username = $userdata['username'] ?? 'unknown';
        $created = serverdatetimesql();
        $logs = [serverdatetimesql(), 'Product Created On ' . serverdatetimesql() . ' by useruid(' . $createdby . ')'];
        $hash = generatenewhash($this->tablename);

        $addtofinalDBVar($name, 'name');
        $addtofinalDBVar($description, 'description');
        $addtofinalDBVar($price, 'price');
        $addtofinalDBVar($unitname, 'unitname');
        $addtofinalDBVar($storeuid, 'storeuid');
        $addtofinalDBVar($available, 'available');
        $addtofinalDBVar($photourl, 'photourl', true);
        $addtofinalDBVar($barcode, 'barcode');
        $addtofinalDBVar($specs, 'specs', 1);
        $addtofinalDBVar($owneruid, 'owneruid');
        $addtofinalDBVar($sold, 'sold');
        $addtofinalDBVar($category, 'category');
        $addtofinalDBVar($subcategory, 'subcategory');
        $addtofinalDBVar($remarks, 'remarks');
        $addtofinalDBVar($status, 'status');
        $addtofinalDBVar($sku, 'sku');
        $addtofinalDBVar($shortcode, 'shortcode');
        $addtofinalDBVar($shortname, 'shortname');
        $addtofinalDBVar($qrcode, 'qrcode');
        $addtofinalDBVar($rating, 'rating');
        $addtofinalDBVar($reviews, 'reviews', 1);
        $addtofinalDBVar($createdby, 'createdby');
        $addtofinalDBVar($createdfor, 'createdfor');
        $addtofinalDBVar($logs, 'logs');
        $addtofinalDBVar($hash, 'hashkey');
        $addtofinalDBVar($created, 'created');


        global $DB;
        if (!$DB) {
            $DB = DB();
        }
        $key = insertintodb($DB, 'products', $data);

        if ($key) {
            DBQUERY()->PRODUCTS_HISTORY()->NewProductHistory($data);
        }
        return $key;
    }
    function ShowProductsbyStoreUID($uidorhashkey, $onlyactive = true, $fieldstoselect = [])
    {
        if (!$uidorhashkey) {
            return false;
        }
        if (!is_numeric($uidorhashkey)) {
            $uidorhashkey = DB_STORES()->getUIDfromHashkey($uidorhashkey) ?? false;
            if (!$uidorhashkey) {
                return false;
            }
        }
        $data = ['storeuid' => $uidorhashkey];

        if ($onlyactive) {
            $data['status'] = 'active';
        }

        return $data = $this->ListFromDB($data, [], $fieldstoselect);
    }

    function getReviewsbyUID($uidorhashkey)
    {
        if (!$uidorhashkey) {
            return false;
        }
        $productdetails = $this->getDetailsbyUIDorHashkey($uidorhashkey);
        if (!$productdetails) {
            return false;
        }
        return $reviews = tryjsondecode($productdetails['reviews']) ?? '';
    }

    function setReviewsbyUID($uidorhashkey, $reviews)
    {
        if (!$uidorhashkey) {
            return false;
        }
        if ($reviews) {
            $reviews = tryjsonencode($reviews);
        }
        return $this->ModifyDBSinglefieldbyUID($uidorhashkey, 'reviews', $reviews);
    }
    function addReviewbyUID($uidorhashkey, $useruid, $rating, $content)
    {
        if (!$uidorhashkey || !$useruid || !$rating || !$content) {
            return false;
        }

        $reviews = $this->getReviewsbyUID($uidorhashkey);
        if ($reviews === false) {
            return false;
        }
        $lastelement = $reviews[count($reviews) - 1] ?? false;
        if (!$lastelement) {
            $count = $lastelement[0] ?? 1;
        }
        $createddate = serverdatetimesql();
        $modifieddate = serverdatetimesql();

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

        $userSUID = $userdetails['uid'];
        $userHash = $userdetails['hashkey'];

        $reviews[] = [$count, $createddate, $modifieddate, $userHash, $rating, $content];
        return $this->setReviewsbyUID($uidorhashkey, $reviews);

    }
    function clearReviewsbyUID($uidorhashkey)
    {
        return $this->setReviewsbyUID($uidorhashkey, []);
    }

    function listProductsbyStatus($status = null, $fieldstoselectarray = '', )
    {
        return DBQUERY()->PRODUCTS()->ListFromDB(['status' => strtolower($status)], $likefields = [], $fieldstoselectarray) ?? false;
    }
    function listActiveProductsStatus($fieldstoselectarray = '')
    {
        return $this->listProductsbyStatus('active', $fieldstoselectarray);
    }
    function listProductsbyStatuswithStock($status = null, $fieldstoselectarray = '')
    {

        $noavailableflag = 0;
        if ($fieldstoselectarray && !in_array('available', $fieldstoselectarray)) {
            $noavailableflag = 1;
            $fieldstoselectarray[] = 'available';
        }
        $list = $this->listProductsbyStatus($status, $fieldstoselectarray);
        if (!$list) {
            return false;
        }
        foreach ($list as $key => $value) {
            if ($value['available'] < 1) {
                unset($list[$key]);
                continue;
            }
            if ($noavailableflag) {
                unset($list[$key]['available']);
            }

        }
        $list = array_values($list);
        return $list;
    }
    function listAvailableandActiveProducts($fieldstoselectarray = '')
    {
        return $this->listProductsbyStatuswithStock('active', $fieldstoselectarray);
    }


}

class DB_PRODUCTS_QUICK_MULTIPLESEARCH
{
    use DBClassSearch;
    public $data;

    public $tablename = 'products';

    private $parentidresults = [];


    public function __construct($data = [], $likefields = [], $fieldstoselectarray = '', $orderby = '', $noindex = 0, $whereappend = ' and ', $dateonlyarray = '', $newdata = false)
    {
        return $this->initialize($data, $likefields, $fieldstoselectarray, $orderby, $noindex, $whereappend, $dateonlyarray, $newdata);
    }

    function FindName($uid)
    {
        return $this->Find($fieldname = 'uid', $contenttosearch = $uid, $exact = true)[0]['name'];
    }

}



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

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



