<?php

    $db = new SQLite3('./api/.db.db');

    if(isset($_POST['request_type']) && $_POST['request_type'] == 'sortApps')
    {
        array_map(function($value, $key) use ($db) {
            $db->exec("UPDATE store SET sort = ". ($key+1) ." WHERE id = $value");
        }, $_POST['itemsSorted'], array_keys($_POST['itemsSorted']));
    }

    if(isset($_POST['request_type']) && $_POST['request_type'] == 'bypass-applock')
    {
        session_start();

        $rowQuery = $db->query("SELECT applock FROM users WHERE id = 1");
        $applock = $rowQuery->fetchArray()[0];

        if($_POST['appPassword'] == $applock)
        {
            $_SESSION['bypass-applock'] = true;

            echo true;
        }
        else
            echo false;
    }

    if(isset($_POST['request_type']) && $_POST['request_type'] == 'deleteIcon')
    {
        header('Content-Type: application/json');
        error_reporting(0);

        $iconPath = 'uploads/icons';

        $rowQuery = $db->query("SELECT icon FROM store WHERE id = ". $_POST['appid']);
        $oldIcon = $rowQuery->fetchArray()[0];

        $newIcon = array_filter(explode(';; ', $oldIcon), function($icon) {
            return $icon != $_POST['icon'];
        });
        
        $response = $db->exec("UPDATE store SET icon = '". implode(';; ', $newIcon) ."' WHERE id = ". $_POST['appid']);

        if($response) {
            // delete icon from storage
            $iconToDelete = $iconPath .'/'. $_POST['icon'];
            if(file_exists($iconToDelete)) {
                unlink($iconToDelete);
            }
        }

        echo json_encode($response);        
    }
?>