<?php
require_once('Main.lib.php');


if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.cookie_lifetime', 315360000);
    ini_set('session.gc_maxlifetime', 315360000);
    session_start();
}



$refreshpage = function () {
    echo '<script>window.location.reload();</script>';
};


function DetectifUrlandMethodisCorrect($url, $condition, $method = 'GET')
{
    if (!$url || !$method) {
        return false;
    }
    $method = strtoupper($method);
    if ($method !== 'GET' && $method !== 'POST') {
        return false;
    }

    $reqtype = $method;

    $GetQuery = parse_url($_SERVER['REQUEST_URI']) ?? '';
    $urlSegments = explode('/', $GetQuery['path']);
    unset($urlSegments[0]);
    $urlSegments = array_values($urlSegments);

    $urlSegments_targetURL = explode('/', $url);
    unset($urlSegments_targetURL[0]);
    $urlSegments_targetURL = array_values($urlSegments_targetURL);
    $url_arguments = [];
    $errors = 0;
    foreach ($urlSegments_targetURL as $key => $value) {
        if (strpos($value, '{') === 0 && strpos($value, '}') === strlen($value) - 1) {
            $url_arguments[trim($value, '{}')] = $key;
            unset($urlSegments_targetURL[$key]);
        }
    }
    $urlSegments_targetURL = array_values($urlSegments_targetURL);
    foreach ($url_arguments as $key => $value) {
        if (!isset($urlSegments[$value])) {
            unset($url_arguments[$key]);
            $errors++;
            continue;
        }
        $url_arguments[$key] = $urlSegments[$value];
        unset($urlSegments[$value]);
    }

    $urlSegments = array_values($urlSegments);

    if ($errors || ($urlSegments !== $urlSegments_targetURL)) {

        return false;
    }

    if (!(strtolower($_SERVER['REQUEST_METHOD']) === strtolower($reqtype)) or $condition === false) {
        return false;
    }
    return true;
}



// function redirect($url, $functiontoexecute, $reqtype = 'GET', $condition = NULL, $functionvariable = '', $caching = false, $exactquery = true)
// {


//     $GetQuery = parse_url($_SERVER['REQUEST_URI']) ?? '';
//     $urlSegments = explode('/', $GetQuery['path']);
//     unset($urlSegments[0]);
//     $urlSegments = array_values($urlSegments);

//     $urlSegments_targetURL = explode('/', $url);
//     unset($urlSegments_targetURL[0]);
//     $urlSegments_targetURL = array_values($urlSegments_targetURL);
//     $url_arguments = [];
//     $errors = 0;
//     foreach ($urlSegments_targetURL as $key => $value) {
//         if (strpos($value, '{') === 0 && strpos($value, '}') === strlen($value) - 1) {
//             $url_arguments[trim($value, '{}')] = $key;
//             unset($urlSegments_targetURL[$key]);
//         }
//     }
//     $urlSegments_targetURL = array_values($urlSegments_targetURL);
//     foreach ($url_arguments as $key => $value) {
//         if (!isset($urlSegments[$value])) {
//             unset($url_arguments[$key]);
//             $errors++;
//             continue;
//         }
//         $url_arguments[$key] = $urlSegments[$value];
//         unset($urlSegments[$value]);
//     }

//     $urlSegments = array_values($urlSegments);

//     if ($errors || ($urlSegments !== $urlSegments_targetURL)) {

//         return false;
//     }

//     if (!(strtolower($_SERVER['REQUEST_METHOD']) === strtolower($reqtype)) or $condition === false) {
//         return false;
//     }


//     if (!$caching) {
//         removecaching();
//     } elseif ($caching) {
//         if ($caching === true) {
//             SetCache1Year();
//         } elseif (is_numeric($caching)) {
//             SetCacheTimeMinutes($caching);
//         } else {
//             SetCache1Year();
//         }
//     }

//     $functiontoexecute($url_arguments, $functionvariable);

// }


function redirecttofile($url, $filename, $reqtype = 'GET', $condition = NULL, $caching = false)
{
    if (!$filename) {
        return false;
    }
    redirect($url, function () use ($filename) {
        if (file_exists($filename)) {
            echo file_get_contents($filename);
        } else {
            echo file_get_contents('pages/messages/404');
        }
    }, $reqtype, $condition, NULL, $caching);
}
function redirecttofileFolder($urlfolder, $reqtype = 'GET', $condition = true, $caching = false)
{
    redirect($urlfolder . '/{filename}', function ($args) use ($urlfolder) {
        $filename = $args['filename'] ?? '';
        $fullpath = $urlfolder . '/' . $filename;
        if (file_exists($fullpath)) {
            echo file_get_contents($fullpath);
            return true;
        } else {
            return false;
        }
    }, $reqtype, $condition, NULL, $caching);
}
/*
redirecttofileFolder('/dist/css');
redirecttofileFolder('/dist/js');
redirecttofileFolder('/dist/alt-theme');
redirecttofileFolder('/assets');
redirecttofileFolder('/assets');
redirecttofileFolder('/plugins/googlefonts');
redirecttofileFolder('/plugins/fontawesome-free/css');
redirecttofileFolder('/plugins/fontawesome-free/webfonts');
redirecttofileFolder('/plugins/bootstrap/js');
*/


function IntStatustoString($status)
{
    switch ($status) {
        case 0:
            return 'New';
        case 1:
            return 'Ongoing';
        case -1:
            return 'Lost';
        case -2:
            return 'Rejected';
        case 2:
            return 'For Follow-up';
        case 3:
            return 'Positive';
        case 4:
            return 'For Completion';
        case 5:
            return 'Completed';
        default:
            return 'Unknown Status';
    }
}

function IntPropertyStatustoString($status)
{
    switch ($status) {
        case 0:
            return 'New';
        case 1:
            return 'Active';
        case -1:
            return 'Defunct';
        case -2:
            return 'Low Priority';
        case 2:
            return 'High Priority';
        case 3:
            return 'High Sales';
        case -3:
            return 'Hidden';
        default:
            return 'Unknown Status';
    }
}

$loginstatus = loginstatus();

$checkusertype = function ($acct_type) use ($loginstatus) {
    if (!$loginstatus) {
        return null;
    }
    return strtolower($loginstatus['userdata']['acct_type']) === strtolower($acct_type);
};



$CurrentUserUID = $loginstatus['userdata']['uid'] ?? false;
$loginstatusAndCurrentUserUID = $loginstatus and $CurrentUserUID;

$useraccountdetails = GetUserDatabyUID($CurrentUserUID);
if ($useraccountdetails) {
    unset($useraccountdetails['password']);
    $current_balance = $useraccountdetails['total_balance'];
    $isUserActive = $useraccountdetails['active'];
    $userNickname = $useraccountdetails['nickname'];
    $userHashkey = $useraccountdetails['hashkey'];
    $userMobileNumber = $useraccountdetails['mnumber'];
}

$IsNormalUser = $checkusertype('user');
$IsUserViewer = $checkusertype('viewer');
$IsUserDisabler = $checkusertype('disabler');
$IsUserUsher = $checkusertype('agent');
$IsUserCoordinator = $checkusertype('coordinator');
$IsUserOperator = $checkusertype('operator');
$IsUserSuperOperator = $checkusertype('super operator');
$IsUserUltimate = $checkusertype('ult');

$IsUserStoreManager = $checkusertype('store manager');
$IsUserStoreOwner = $checkusertype('store owner');
$IsUserRider = $checkusertype('rider');
$IsUserRegionalDirector = $checkusertype('regional director');
$IsUserAudit = $checkusertype('audit');
$IsUserAdminStaff = $checkusertype('admin staff');
$IsUserTeamLeader = $checkusertype('team leader');

$CurrentUserType = $loginstatus['userdata']['acct_type'] ?? false;
$CurrentParentUID = $loginstatus['userdata']['parentuid'] ?? false;
$CurrentUserHash = $loginstatus['userdata']['hashkey'] ?? false;
$CurrentUserNickname = $loginstatus['userdata']['nickname'] ?? false;
$CurrentUserMobileNumber = $loginstatus['userdata']['mnumber'] ?? false;

redirect('/isloggedin', function () {
    global $loginstatus;
    $loginstatus = $loginstatus ? true : false;
    json_array_echo($loginstatus);
}, 'GET', true);

redirect('/isExec', function ($urlArguments) {
    global $CurrentUserUID;
    $exec = GetUserExec_Command($CurrentUserUID);
    ClearUserExec_Command($CurrentUserUID);
    json_array_echo($exec);
}, 'GET', $loginstatusAndCurrentUserUID);





redirecttofile('/', 'pages/login.html', 'GET', !$loginstatus);

redirecttofile('/', 'starter.html', 'GET', $loginstatus);

redirect('/loginnow', function () {

    if (!isset($_POST['usernumber']) or !isset($_POST['userpassword'])) {
        json_array_echo(NULL);
        return NULL;
    }
    $keep_alive = $_POST['keepalive'] === 'true' ? true : false;
    loginnow($_POST['usernumber'], $_POST['userpassword'], $keep_alive);
    if (!loginstatus()) {
        json_array_echo(false);
        return false;
    }
    json_array_echo(true);
    return true;
}, 'POST', true);

redirect('/logoutnow', function () {
    logoutnow();
    header("Location: http://" . $_SERVER['HTTP_HOST']);
    echo "<script> let urlWithoutParams = window.location.href.split('?')[0];
    window.location.href = urlWithoutParams; </script>";

}, 'GET', $loginstatusAndCurrentUserUID);

redirect('/loginnow/via/cookies', function () {
    $SESSION_ID = $_POST['SESSID'] ?? false;
    if (!$SESSION_ID) {
        json_array_echo(false);
        return false;
    }
    $login = tryloginwcookies($SESSION_ID);
    if (!$login) {
        json_array_echo(false);
        return false;
    }
    if ($login) {
        json_array_echo(true);
        return true;
    }
}, 'POST', true);

$htmlEcho = function ($url, $string) {
    redirect($url, function () use ($string) {
        echo $string . '';
    }, $reqtype = 'GET', $loginstatusAndCurrentUserUID);
};

redirecttofile('/HomePage', 'pages/slvl/user/defaultuser', 'GET', $IsNormalUser);
redirecttofile('/HomePage', 'pages/slvl/user/teamleader', 'GET', $IsUserTeamLeader);
redirecttofile('/HomePage', 'pages/slvl/usher/home_usher', 'GET', $IsUserUsher);

redirecttofile('/HomePage', 'pages/slvl/coordinator/home_coordinator', 'GET', $IsUserCoordinator);
redirecttofile('/HomePage', 'pages/slvl/operator/home_operator', 'GET', $IsUserOperator);

redirecttofile('/HomePage', 'pages/slvl/superoperator/home_superoperator', 'GET', $IsUserSuperOperator);
redirecttofile('/HomePage', 'pages/slvl/ultimate/home_ultimateALT', 'GET', $IsUserUltimate);

redirecttofile('/HomePage', 'pages/slvl/disabler/home_disabler', 'GET', $IsUserDisabler);

redirecttofile('/NewLeads', 'pages/slvl/all/NewLeads', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/ViewLeadDetails', 'pages/slvl/all/ViewLeadDetails', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/ListLeads', 'pages/slvl/all/ListLeads', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/ListProperties', 'pages/slvl/all/ListProperties', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/NewProperty', 'pages/slvl/all/NewProperty', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/ViewPropertyDetails', 'pages/slvl/all/ViewPropertyDetails', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/ListLeadsByProperty', 'pages/slvl/all/LeadsByProperty', 'GET', $loginstatusAndCurrentUserUID);

redirecttofile('/ViewAllPhotos', 'pages/slvl/all/ViewAllPhotos', 'GET', $loginstatusAndCurrentUserUID);
redirecttofile('/PhotoViewer', 'pages/slvl/all/PhotoViewer', 'GET', $loginstatusAndCurrentUserUID);

redirecttofile('/AccountSettings', 'pages/slvl/all/account_settings', 'GET', $loginstatusAndCurrentUserUID);




$PropertyCategoryList = [
    'Condominium',
    'House'
];

$PropertySubCategoryList = [
    'Bungalow',
    'Tiny House',
    'Capsule'
];



redirect('/DB', function () {

    if (file_exists('settings/DBInitialized')) {
        echo 'DB Initialized';
    } else {
        echo 'DB Not Initialized';
    }

}, 'GET', true);

redirect('/CheckUser/{userid}', function ($urlArguments) {
    $userid = $urlArguments['userid'];
    if (checkifuserexists($userid)) {
        echo 'exists';
    } else {
        echo 'does not exist';
    }

}, 'GET', true);


redirect('/InitDB', function () {
    try {
        echo 'Initializing DB...' . '<br>';
        RunDBInit();
        echo 'DB Initialized' . '<br>';
    } catch (Exception $e) {
        echo 'Unable to Initialize DB... ' . $e->getMessage() . '<br>';
    }
    echo 'Initializing MainUser...' . '<br>';

    if (DB_USERS()->NewUser($GLOBALS['defaultAdminAppUser'], $GLOBALS['defaultAdminAppPassword'], '', 'ult', '', 1)) {
        echo 'MainUser Initialized' . '<br>';
        file_put_contents('settings/DBMainUserInitialized', 'true');
    } else {
        echo 'Unable to Initialize MainUser. Please try again later.' . '<br>';
    }

}, 'GET', true);



redirect('/Datalist/{textid}', function ($urlArguments) {
    $textid = $urlArguments['textid'];
    $echoArrayDatalist = function ($targettextid, $arraynameforglobal) use ($textid) {
        if (!$targettextid) {
            return false;
        }
        global $$arraynameforglobal;
        if ($targettextid == $textid) {
            json_array_echo($$arraynameforglobal);
        }
    };


    $echoArrayDatalist('NewPropertyCategory', 'PropertyCategoryList');
    $echoArrayDatalist('NewPropertySubCategory', 'PropertySubCategoryList');

}, 'GET', $loginstatusAndCurrentUserUID);




function TryToInsertFiletoDB($category, $Filename, $tempfilename, $error)
{
    if ($error) {
        return false;
    }

    if ($tempfilename and $Filename) {
        if (!file_exists($tempfilename)) {
            return false;
        }
        $file = file_get_contents($tempfilename);
        if (!$file) {
            return false;
        }
        $file = DBQUERY()->FILE_LIST()->InsertFileListandFileContentFromFile($tempfilename, $Filename, $toDBtrueifFalseSateLocationtoSave = false, $description = '', $tags = $category, $categories = $category, $hidden = 0);
    }
    return $file;
}

/*
redirect('/File/Upload/{category}', function ($urlArguments) {

    $category = $urlArguments['category'] ?? '';
    $Filename = $_FILES['file']['name'];
    $tempfilename = $_FILES['file']['tmp_name'];
    $error = $_FILES['file']['error'];


    if ($error) {
        json_array_echo(false);
        return false;
    }

    if ($tempfilename and $Filename) {
        if (!file_exists($tempfilename)) {
            json_array_echo(false);
            return false;
        }
        $file = file_get_contents($tempfilename);
        if (!$file) {
            json_array_echo(false);
            return false;
        }
        //  $file = insertFileContentsintoDB($tempfilename,$Filename,false);
        $file = DBQUERY()->FILE_LIST()->InsertFileListandFileContentFromFile($tempfilename, $Filename, $toDBtrueifFalseSateLocationtoSave = false, $description = '', $tags = $category, $categories = $category, $hidden = 0);
    }



    if ($file and is_numeric($file)) {
        $file = DBQUERY()->FILE_LIST()->getFileListHashkeybyUID($file);
    } else {
        json_array_echo(false);
        return false;
    }
    json_array_echo($file);
    return $file;

}, 'POST', $loginstatus);

*/



redirect('/File/Upload/{category}', function ($urlArguments) {

    $category = $urlArguments['category'] ?? '';
    $Filename = $_FILES['file']['name'];
    $tempfilename = $_FILES['file']['tmp_name'];
    $error = $_FILES['file']['error'];

    $file = TryToInsertFiletoDB($category, $Filename, $tempfilename, $error);

    if (!$file) {
        json_array_echo(false);
        return false;
    }

    if ($file and is_numeric($file)) {
        $file = DBQUERY()->FILE_LIST()->getFileListHashkeybyUID($file);
    } else {
        json_array_echo(false);
        return false;
    }
    json_array_echo($file);
    return $file;

}, 'POST', $loginstatus);



redirect('transaction/view/details/currentuploadedfiles', function () {
    return false;
    $transaction_hashkey = $_POST['currenttarget'] ?? false;
    if (!$transaction_hashkey) {
        json_array_echo(false);
        return false;
    }
    if (is_numeric($transaction_hashkey)) {
        json_array_echo(false);
        return false;
    }
    $transactiondata = GetTransactionDatabyUID($transaction_hashkey, ['files']) ?? false;
    if (!$transactiondata) {
        json_array_echo(false);
        return false;
    }
    $transactionfiles = $transactiondata['files'] ?? false;
    if (!$transactionfiles) {
        json_array_echo(false);
        return false;
    }
    // $transactionfiles = $transactionfiles;
    $transactionfiles = json_decode($transactionfiles, 1);

    if (!is_array($transactionfiles)) {
        return false;
    }
    $File_Details_Array = [];
    $final_array = [];


    // e ($transactionfiles);
    foreach ($transactionfiles as $file_hashkey) {
        $fileDetails = getFileListDetails($file_hashkey, ['hashkey', 'contentuid', 'description', 'filename', 'tags', 'added']) ?? false;
        if ($fileDetails) {
            $File_Details_Array[] = $fileDetails;
        }
    }



    $getThumbnailbyextenesion = function ($filename) {


        if (!$filename) {
            return '';
        }
        $ext = pathinfo($filename, PATHINFO_EXTENSION) ?? false;
        if ($ext == 'pdf') {
            return 'assets/pdf.png';
        } elseif ($ext == 'doc') {
            return 'assets/doc.png';
        } elseif ($ext == 'docx') {
            return 'assets/doc.png';
        } elseif ($ext == 'xls') {
            return 'assets/xls.png';
        } elseif ($ext == 'xlsx') {
            return 'assets/xls.png';
        } elseif ($ext == 'ppt') {
            return 'assets/ppt.png';
        } elseif ($ext == 'pptx') {
            return 'assets/ppt.png';
        } elseif ($ext == 'jpg') {
            return 'assets/img.png';
        } elseif ($ext == 'jpeg') {
            return 'assets/img.png';
        } elseif ($ext == 'png') {
            return 'assets/img.png';
        } elseif ($ext == 'tiff') {
            return 'assets/img.png';
        } elseif ($ext == 'svg') {
            return 'assets/img.png';
        } elseif ($ext == 'webp') {
            return 'assets/img.png';
        } elseif ($ext == 'png') {
            return 'assets/img.png';
        } else {
            return '';
        }
    };

    foreach ($File_Details_Array as $key => $fileList_details) {
        $final_array[$key]['hashkey'] = $File_Details_Array[$key]['hashkey'];
        $contentsize = getFileContentDetails($fileList_details['contentuid'])['size_in_bytes'] ?? false;

        $final_array[$key]['size'] = $contentsize;
        $final_array[$key]['name'] = $File_Details_Array[$key]['filename'];
        $final_array[$key]['url'] = '?file/download/' . $File_Details_Array[$key]['hashkey'];
        $final_array[$key]['thumbnail'] = $getThumbnailbyextenesion($File_Details_Array[$key]['filename']);
    }


    json_array_echo($final_array);
    return $final_array;


}, 'POST', $loginstatus);

redirect('file/download', function () {



}, 'GET', $loginstatus);

redirect('filecontent/viewdetails', function () {



}, 'POST', $loginstatus);


redirect('/p/{pagename}/s/{val}', function ($urlArguments) {
    $pagename = $urlArguments['pagename'] ?? '';
    $val = $urlArguments['val'] ?? '';
    global $loginstatus;
    $publicPages = [
        'ReferProperty'
    ];
    if (!$loginstatus && !in_array($pagename, $publicPages)) {
        echo '<script>window.location.href = "/";</script>';
        return false;
    }


    if (!$pagename) {
        return false;
    }

    $echopage = function ($targetname) use ($pagename, $val, $publicPages) {
        if ($targetname !== $pagename) {
            return false;
        }
        if (in_array($pagename, $publicPages)) {
            echo '<script>DontInitialize=1;</script>';
        }
        $base64toobject = urlSafeBase64ToObject($val);

        $val = urldecode($val);
        if (str_contains($val, '{')) {

        } elseif (str_contains($val, ',')) {
            $val = explode(',', $val);
            $val = tryjsonencode($val);
        } else {
            $val = "'" . $val . "'";
        }

        $html = file_get_contents('starter.html');
        $pagehtml = '';
        if (file_exists('pages/' . $pagename)) {
            $pagehtml = file_get_contents('pages/' . $pagename) ?? '';
            if ($pagehtml) {
                $pagehtml = base64_encode($pagehtml);
            }
        }


        $gotoscript = "<script>$(document).ready(function () {
        gotoPage('" . $pagename . "', " . $val . ",0,0,`" . $pagehtml . "`);
    
    });</script>";

        $res = $html . $gotoscript;
        echo ($res);
    };

    $echopage($pagename);


}, 'GET', true);

redirect('/user/changemypassword', function () {

    $current_password = $_POST['current_password'] ?? false;
    $new_password = $_POST['new_password'] ?? false;
    $new_confirm_password = $_POST['new_confirm_password'] ?? false;
    if (!$current_password or !$new_password or !$new_confirm_password) {
        json_array_echo('Enter Old Password, New Password and Password Confirmation.');
        return false;
    }

    global $CurrentUserUID;
    $Current_password_DB = GetUserDatabyUID($CurrentUserUID)['password'] ?? false;
    if (!$Current_password_DB) {
        json_array_echo('Incorrect Old Password. Please enter you old password correctly.');
        return false;
    }


    if (strlen($new_password) < 6) {
        json_array_echo('Password is less than 6 digits');

        return false;
    }

    if ($new_password !== $new_confirm_password) {
        json_array_echo('Confirmation Password does not match new password.');

        return false;
    }

    if ($Current_password_DB !== hash('sha256', $current_password)) {
        json_array_echo('Incorrect Old Password. Please enter you old password correctly.');

        return false;
    }
    $new_password_hash = hash('sha256', $new_password);
    ModifyUser(['password' => $new_password_hash], $CurrentUserUID);

    $Current_password_DB_afterchange = GetUserDatabyUID($CurrentUserUID)['password'] ?? false;
    if (!$Current_password_DB_afterchange) {
        json_array_echo('Error. Please Try Again Later');
        json_array_echo(false);
        return false;
    }

    if ($Current_password_DB_afterchange === $new_password_hash) {
        json_array_echo(true);
        return true;
    } else {
        json_array_echo('Error. Try Again Later.');
        return false;
    }
    json_array_echo('Error.');

    return false;
}, 'POST', $loginstatusAndCurrentUserUID);

redirect('/account_settings/details', function () {
    $DB = DB();
    global $CurrentUserUID;
    if (!$CurrentUserUID) {
        return false;
    }
    $details = DB_USERS($DB)->GetUserDatabyUID($CurrentUserUID, ['mnumber', 'username', 'nickname', 'created', 'referralcode', 'photourl']) ?? false;
    $additionaldetails = DB_USERINFO($DB)->GetbyTargetUserUID($CurrentUserUID) ?? false;
    $res['mobile'] = $details['mnumber'] ?? '';
    $res['name'] = $details['username'] ?? '';
    $res['nickname'] = $details['nickname'] ?? '';
    $res['joined'] = $details['created'] ?? '';
    $res['referralcode'] = $details['referralcode'] ?? '';
    $res['email'] = $additionaldetails['email'] ?? '';
    $res['fullname'] = $additionaldetails['fullname'] ?? '';
    $res['photourl'] = $details['photourl'] ?? '';
    $res['landline'] = $additionaldetails['landline'] ?? '';
    if (tryjsondecode($res['photourl'])) {
        $res['photourl'] = tryjsondecode($res['photourl']);
    }



    if (!$res['mobile']) {
        $res['mobile'] = $additionaldetails['mobile'];
    }

    $userinfo_photourl = $additionaldetails['photourl'] ?? null;
    $res['photourl2'] = tryjsondecode($userinfo_photourl) ?? '';

    json_array_echo($res);


    //add userinfo DB

}, 'GET', $loginstatusAndCurrentUserUID);


$JSCommands = [];

$JSCommands['SetDarkMode'] = "UISetDarkMode();";



redirect('/User/Settings/Details', function () {
    $settings = GET_CurrentUserInternalSettings();
    json_array_echo($settings);

}, 'POST', $loginstatusAndCurrentUserUID);

redirect('/User/Settings/Run/Scripts', function () {
    global $JSCommands;
    $settings = GET_CurrentUserInternalSettings();
    $darkmode = $settings['darkmode'] ?? false;
    if ($darkmode) {
        echo $JSCommands['SetDarkMode'];
    }


}, 'POST', $loginstatusAndCurrentUserUID);

function GET_CurrentUserInternalSettings()
{
    global $CurrentUserUID;
    global $DB;
    if (!$DB) {
        $DB = DB();
    }
    if (!$CurrentUserUID && !$DB) {
        return false;
    }
    return DBQUERY($DB)->USERS()->Settings()->Get($CurrentUserUID);
}



redirect('/RequestData/File/{hash}', function ($urlArguments) {
    $hash = $urlArguments['hash'] ?? false;
    if (!$hash) {
        return;
    }
    if (is_numeric($hash)) {
        return;
    }
    $hash = DBQUERY()->FILE_LIST()->getDetailsbyUIDorHashkey($hash);
    if (!$hash) {
        return;
    }
    $contentuid = $hash['contentuid'] ?? false;
    if (!$contentuid) {
        return;
    }
    $contenthash = DBQUERY()->FILE_CONTENT()->getFileContentHashkeybyUID($contentuid);
    if (!$contenthash) {
        return;
    }


    $setheaderCACHE = function () {
        header("Cache-Control: public, max-age=31536000"); //1 year
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + 31536000) . " GMT");
    };


    $filedirectory = 'files/';
    $fullfilelocation = $filedirectory . $contenthash;

    $mimecontent = mime_content_type($fullfilelocation);



    $maximgheight = 4000;
    $maximgwidth = 4000;
    $imgquality = 50;

    if (str_contains($mimecontent, 'png')) {
        $newjpglocation = 'filestor/PNGTOWEBP/' . $contenthash;
        if (file_exists($newjpglocation)) {

            $setheaderCACHE();

            //echoFile($newjpglocation); // This function Does not work in the meantime
            header('Content-Type: ' . $mimecontent); //replacement for echoFile
            echo file_get_contents($newjpglocation);
            return;
        }

        PNGtoWebP($fullfilelocation, $newjpglocation, $maximgwidth, $maximgheight, $imgquality);

        if (file_exists($newjpglocation)) {

            $setheaderCACHE();
            //echoFile($newjpglocation); // This function Does not work in the meantime
            header('Content-Type: ' . $mimecontent); //replacement for echoFile
            echo file_get_contents($newjpglocation);
            return;
        }

    }

    $setheaderCACHE();
    header('Content-Type: ' . $mimecontent);

    //echoFile($fullfilelocation); // This function Does not work in the meantime
    header('Content-Type: ' . $mimecontent); //replacement for echoFile
    echo file_get_contents($fullfilelocation);

    return;
}, 'GET', true);


function RequestPhotos($hash, $type)
{
    if (!$hash || !$type) {
        return false;
    }
    global $CurrentUserType;
    global $CurrentUserUID;
    if (!$CurrentUserType || !$CurrentUserUID) {
        return false;
    }

    $photourl = null;

    if ($type === 'ProductMarket') {

        $productDetails = DBQUERY()->PRODUCTS()->getDetailsbyUIDorHashkey($hash);
        if (!$productDetails) {
            return false;
        }
        $status = $productDetails['status'];
        $productStoreID = $productDetails['storeuid'];
        $isUltimateUser = WhatUserType()->IsUltimate();
        $isStoreManager = WhatUserType()->IsStoreManager();
        $isStoreOwner = WhatUserType()->IsStoreOwner();
        $storeManager = false;
        $storeOwner = false;



        $getStoreManagerAndOwner = function () use ($productStoreID, &$storeManager, &$storeOwner) {
            $storeDetails = DB_STORES()->getDetailsbyUIDorHashkey($productStoreID);
            if (!$storeDetails) {
                return false;
            }
            $storeManager = $storeDetails['manageruid'];
            $storeOwner = $storeDetails['owneruid'];
            return ['owner' => $storeOwner, 'manager' => $storeManager];
        };

        $allowed_flag = false;
        if ($status !== 'active') {
            if ($isUltimateUser) {
                $allowed_flag = true;
            } elseif ($isStoreManager || $isStoreOwner) {
                $storeD = $getStoreManagerAndOwner();
                if (!$storeD) {
                    return false;
                }
                if ($storeManager === $CurrentUserUID) {
                    $allowed_flag = true;
                } elseif ($storeOwner === $CurrentUserUID) {
                    $allowed_flag = true;
                }

            }
        } else {
            $allowed_flag = true;
        }


        if (!$allowed_flag) {
            return false;
        }

        $photourl = $productDetails['photourl'];
        $photourl = tryjsondecode($photourl);

    } elseif ($type === 'User') {
        $photourl = DBQUERY()->USERS()->GetUserDatabyUID($hash)['photourl'] ?? false;
    }

    return $photourl;

}



redirect('/Request/Photos/{type}', function ($urlArguments) {
    $type = $urlArguments['type'] ?? false;
    $hash = $_POST['target'] ?? false;
    if (!$type) {
        return false;
    }

    if (!$hash || is_numeric($hash)) {
        json_array_echo(false);
        return false;
    }

    $photourls = null;
    if ($type === 'ProductMarket') {
        json_array_echo(RequestPhotos($hash, $type));
        return;

    } elseif ($type === 'User') {
        $photourls = DBQUERY()->USERS()->GetUserDatabyUID($hash)['photourl'] ?? false;
    } elseif ($type === 'StoreMarket') {
        $photourls = DBQUERY()->STORES()->getphotoURLsbyUIDorHASH($hash);
    }



    if (!$photourls) {
        json_array_echo(false);
        return false;
    }

    $photourls = tryjsondecode($photourls);
    json_array_echo($photourls);
    return;

}, 'POST', $loginstatusAndCurrentUserUID);



class Routes_Main
{

    function echoHashfromArray($array)
    {
        if (!$array) {
            return false;
        }
        return json_array_echo(ArraytoHash($array));
    }

    function echoDataSuccess($data)
    {
        if (!$data) {
            $finres['success'] = false;
            json_array_echo($finres);
            return false;
        }
        $finres['success'] = true;
        $finres['Details'] = $data;
        json_array_echo($finres);
        return true;
    }
    /**
     * echoHashSuccess
     * Echos as hash as json false if not a proper hash
     * echoes false if hash is false empty or integer and if less than  $hash characters
     * @param mixed $hash = hash to echo
     * @param mixed $hash_characters Number of characters a hash should be default is 72
     * @return bool
     */
    function echoHashSuccess($hash, $hash_characters = 72)
    {
        if (!$hash || is_numeric($hash) || strlen($hash) !== $hash_characters) {
            json_array_echo(false);
            return false;
        }

        json_array_echo($hash);
        return true;
    }

    function echoRedirectDataandHash($url, $datafunction, $conditiontrue = true, $reqtype = 'POST')
    {
        if (!$url || !$datafunction) {
            return false;
        }

        $hashurl = $url . '/hash';

        $urldetect = DetectifUrlandMethodisCorrect($url, $conditiontrue, $reqtype);
        $hashurldetect = DetectifUrlandMethodisCorrect($hashurl, $conditiontrue, $reqtype);

        if (!$urldetect && !$hashurldetect) {
            return false;
        }

        $data = $datafunction();

        redirect($url, function () use ($data) {
            json_array_echo($data);
        }, 'POST', true);


        redirect($hashurl, function () use ($data) {
            if (!$data) {
                json_array_echo(null);
                return null;
            }

            $hash = ArraytoHash($data);
            json_array_echo($hash);
            return $hash;
        }, 'POST', true);

    }

    function DetectifUrlandMethodisCorrect($url, $condition, $method = 'GET')
    {
        return DetectifUrlandMethodisCorrect($url, $condition, $method);
    }

    function getTargetHashPOST()
    {
        $target = $_POST['target'] ?? false;
        if (!$target || is_numeric($target)) {
            return false;
        }
        return $target;
    }





}

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



require_once('routes/products.php');
require_once('routes/debug.php');
require_once('routes/debug.php');
//require_once('routes/leads.php');
require_once('routes/ultimate.php');
require_once('routes/properties.php');
//require_once('routes/referralcodes.php');
require_once('routes/users.php');
require_once('routes/transactions.php');
require_once('routes/accounting.php');
require_once('routes/store.php');





