<?php

require_once(MH_DIR_CONFIG . 'config_api/classes/apibeez.php');

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & (PHP_VERSION_ID < 80400 ? ~2048 : ~0));
ini_set('display_errors', mh_cfg('MAILBEEZ_API_DEBUG', 0));


class api_public_sitezen_cleanup extends apibeez
{

    function __construct()
    {
        parent::__construct();
        $this->has_get = true;
        $this->has_post = true;
        mh_session_write_close();
    }


    function _post($request_data, $payload_data)
    {
        $email_address = $_POST['email_address'] ?? false;
        $result = $this->removeAccount($email_address);
        session_destroy();
        $this->template_dir = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'configbeez/config_sitezen/views/';
        $this->template = 'remove_account';
        $data = [
            'endpoint' => false,
            'result' => $result
        ];
        header("Content-Type: " . 'text/html');
        echo $this->render($data);
        mh_exit();
    }

    // GET api/public/v1.0/sitezen/cleanup/
    // requires HTTP_X_TOKEN and HTTP_X_EMAIL_PATTERN
    function _get($request_data, $payload_data)
    {
        if (isset($_SERVER['HTTP_X_TOKEN']) && $_SERVER['HTTP_X_TOKEN'] == mh_cfg('MAILBEEZ_CONFIG_SITEZEN_TOKEN') && isset($_SERVER['HTTP_X_EMAIL_PATTERN'])) {
            // remove test accounts
            $emailPattern = $_SERVER['HTTP_X_EMAIL_PATTERN'];
            $result = $this->removeAccount($emailPattern, true);

        } else {
            $result = 'invalid request';
        }
        $return = [
            'result' => $result,
        ];
        echo json_encode($return);
        mh_exit();

    }


    private function removeAccount($email_address, $pattern = false)
    {

        if ($pattern) {
            $emailPattern = $email_address;

            // avoid dangerous situations...
            // only match known testzen email patterns
            if (!str_contains($emailPattern, '%') || !str_contains($emailPattern, '@gmail.com') || !str_contains($emailPattern, 'p9893992')) {
                return "invalid email pattern: '" . $emailPattern . "'";
            }
            $query = mh_db_query("SELECT customers_id FROM " . TABLE_CUSTOMERS . " where customers_email_address like '" . $emailPattern . "' limit 1");
        } else {
            $query = mh_db_query("SELECT customers_id FROM " . TABLE_CUSTOMERS . " where customers_email_address = '" . $email_address . "'");
        }

        $customerIds = [];
        while ($row = mh_db_fetch_array($query)) {
            $customerIds[] = $row['customers_id'];
        }

        if (empty($customerIds)) {
            $result = "no matching customer accounts for '" . $email_address . "'";
        } else {
            $customerIdsInClause = implode(',', $customerIds);
            mh_db_query("DELETE FROM " . TABLE_CUSTOMERS . " WHERE customers_id IN ($customerIdsInClause)");
            mh_db_query("DELETE FROM " . TABLE_ADDRESS_BOOK . " WHERE customers_id IN ($customerIdsInClause)");
            mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_INFO . " WHERE customers_info_id IN ($customerIdsInClause)");

            mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_BASKET . " WHERE customers_id IN ($customerIdsInClause)");
            mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_BASKET_ATTRIBUTES . " WHERE customers_id IN ($customerIdsInClause)");
            mh_db_query("DELETE FROM " . TABLE_WHOS_ONLINE . " WHERE customer_id IN ($customerIdsInClause)");
            mh_db_query("DELETE rd, r FROM " . TABLE_REVIEWS_DESCRIPTION . " rd INNER JOIN " . TABLE_REVIEWS . " r ON rd.reviews_id = r.reviews_id WHERE r.customers_id IN ($customerIdsInClause)");

            if (in_array(mh_cfg('MH_SITEZEN_PLATFORM'), ['gambio', 'modified-shop'] )) {
                mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_STATUS_HISTORY . " WHERE customers_id IN ($customerIdsInClause)");
                mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_IP . " WHERE customers_id IN ($customerIdsInClause)");
                mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_WISHLIST . " WHERE customers_id IN ($customerIdsInClause)");
                mh_db_query("DELETE FROM " . TABLE_CUSTOMERS_WISHLIST_ATTRIBUTES . " WHERE customers_id IN ($customerIdsInClause)");
                mh_db_query("DELETE FROM " . mh_cfg('TABLE_CUSTOMERS_MEMO', 'customers_memo') . " WHERE customers_id IN ($customerIdsInClause)");
            }


            $result = 'success, customer ids: ' . $customerIdsInClause;
        }
        return $result;
    }
}