<?php

    $aJsonRespond = [];
    $sModuleDir   = basename(dirname(__DIR__));
    // require config for Constants and DB access
    require(dirname(dirname(dirname(__DIR__))).'/config.php');
    // Check if user has enough rights to do this:
    // initialize json_respond array  (will be sent back)
    try{
        if (!class_exists('admin', false)){require(WB_PATH.'/framework/class.admin.php');}
        $admin = new admin('Modules', 'module_view', FALSE, FALSE);
    // first read and validate the $_POST arguments
        $aAllowedActions = ['toggle_active_status'];
        $sRequestAction  = $_POST['action'] ?:'';
        // test if action value is in allowed list of actions
        if ( !in_array($sRequestAction, $aAllowedActions)) {
            throw new Exception('no valid "action" was set');
        }
        $sRequestIdKey = $_POST['iRecordId'];
//        $iIdKey = $admin->checkIDKEY('iRecordId');
//        $iIdKey = $admin->checkIDKEY('iRecordId', 0, '', true);
        $iIdKey = $sRequestIdKey;
        if (!($iRequestRecordId = (int)$iIdKey ?: 0)) {
            throw new Exception('no valid RecordId was set '.$iRequestRecordId);
        }
        if (!($admin->is_authenticated() && $admin->get_permission($sModuleDir, 'module'))) {
            throw new Exception('You\'re not allowed to make changes to Module: ['.$sModuleDir.']');
        }
        switch ($sRequestAction):
            case 'toggle_active_status':
                // Check the Parameters
                $sql = 'UPDATE `'.TABLE_PREFIX.'mod_droplets` SET '
                     . '`active`= (`active` IS NOT TRUE) '
                     . 'WHERE `id`='.$iRequestRecordId;
                if (!(bool)$database->query($sql)) {
                    throw new Exception('DB access fail ['.$database->get_error().']');
                }
                break;
            default:
                throw new Exception('no valid "action" was set ');
                break;
        endswitch;
        $aJsonRespond['message'] = 'Activity Status successfully changed';
        $aJsonRespond['success'] = true;
//        $aJsonRespond['sIdKey']  = $admin->getIDKEY($iIdKey);
        $aJsonRespond['sIdKey']  = $iIdKey;
    } catch (Exception $e) {
        $aJsonRespond['message'] = $e->getMessage();
        $aJsonRespond['success'] = false;
//        $aJsonRespond['sIdKey']  = $admin->getIDKEY($iIdKey);
        $aJsonRespond['sIdKey']  = $iIdKey;
    }
    // echo the json_respond to the ajax function
    exit(json_encode($aJsonRespond));
