<?php


class DB_STORES
{
    public $DB = false;
    public $tablename = 'stores';

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

    }

    public function GenerateStoreCode($category, $num=null, $length = 8, )
    {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
        $charactersLength = strlen($characters);
        $storeCode = '';
        if(!$num){
            $num = rand(1,99);
        }

        // Generate a random alphanumeric string
        for ($i = 0; $i < $length; $i++) {
            $storeCode .= $characters[rand(0, $charactersLength - 1)];
        }
        $categoryPrefix = substr($category, 0, 2);
        $categorySuffix = substr($category, -2, 2);
        $cat = $categoryPrefix . $categorySuffix;
        $storeCode = date('Y') . '-' . $cat . '-' . $num . '-' . $storeCode;
        return $storeCode;
    }

    private function generateStoreCodeUnique($storeCodeArray, $category, $num = '', $length = 8)
    {
        $storeCodeUnique = false;

        while (!$storeCodeUnique) {
            $newstorecode = $this->GenerateStoreCode($category, $num, $length = 8);
            if (!in_array(strtoupper($storeCodeUnique), $storeCodeArray)) {
                $storeCodeUnique = $newstorecode;
                break;
            }
        }


        return $newstorecode;
    }
    function generateNewStoreCodefromDB($category, $num = '', $length = 8)
    {
        $storecodes = $this->ListFromDB([], [], ['storecode']);
        if (!$storecodes) {
            $storecodes = [];
        }
        $storecodes = array_column($storecodes, 'storecode');
        $targetdateYEARMONTH = date('Y') . '-' . date('m');
        $datecreated = $this->ListbyDateCreated($targetdateYEARMONTH);
        $newnum = (count($datecreated)) + 1;
        if (!$num) {
            $num = $targetdateYEARMONTH . '-' . $newnum;
        }
        $uniqueStoreCode = $this->generateStoreCodeUnique($storecodes, $category, $num, $length);
        return $uniqueStoreCode;
    }

    function NewStore($name, $description, $owneruid, $manageruid, $storeAddress, $category = '', $subcategory = '', $photourl = '', $storecode = '', $status = 'active', $specs = '', $additionaldata = '', $remarks = '', $createdby = '')
    {

        if (!$name || !$description || !$owneruid || !$manageruid || !$storeAddress) {
            return false;
        }
        $GetUserDetails = function ($useruid) {
            if (!$useruid) {
                return false;
            }
            $details = DBQUERY()->USERS()->GetUserDatabyUID($useruid);
            return $details;
        };

        $addtoDataifNotEmpty = function ($varname, $varvalue) use (&$data) {
            if (!$varname || !$varvalue) {
                return false;
            }
            if (is_array($varvalue)) {
                $varvalue = tryjsonencode($varvalue);
            }
            $data[$varname] = $varvalue;
        };

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

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

        $owner_details = $GetUserDetails($owneruid);
        if (!$owner_details) {
            return false;
        }
        $manager_details = $GetUserDetails($manageruid);
        if (!$manager_details) {
            return false;
        }


        if (!MARKET_MAIN()->isNewTransactionAllowed($createdby_details, $manager_details, $owner_details)) {
            return false;
        }


        if (!$storecode) {
            $storecode = $this->generateNewStoreCodefromDB($category);
        }

        $datetimenow = serverdatetimesql();
        $hashkey = $this->GenerateNewHash();
        $logs = [$datetimenow, 'Created New Store by useruid(' . $createdby . ') at ' . $datetimenow];
        $data = [
            'hashkey' => $hashkey,
            'created' => $datetimenow,
            'modified' => $datetimenow,
            'logs' => $logs,
            'name' => $name,
            'description' => $description,
            'owneruid' => $owneruid,
            'manageruid' => $manageruid,
            'createdby' => $createdby,
            'address' => $storeAddress
        ];


        $addtoDataifNotEmpty('category', $category);
        $addtoDataifNotEmpty('subcategory', $subcategory);
        $addtoDataifNotEmpty('photourl', $photourl);
        $addtoDataifNotEmpty('storecode', $storecode);
        $addtoDataifNotEmpty('status', $status);
        $addtoDataifNotEmpty('specs', $specs);
        $addtoDataifNotEmpty('additionaldata', $additionaldata);
        $addtoDataifNotEmpty('remarks', $remarks);

        $insert = $this->InsertIntoDB($data);
        return $insert;
    }
}

class DB_STORES_QUICK_MULTIPLESEARCH
{
    use DBClassSearch;
    public $data;

    public $tablename = 'stores';

    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_STORES($DB = false)
{
    return new DB_STORES($DB);
}

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