<?php
require_once("../layouts/members/head.php");

if (!in_array($user_data['usertype'], ['Admin', 'White Label'], true)) {
    require_once("404.php");
    require_once("../layouts/members/foot.php");
    exit;
}

/*
|--------------------------------------------------------------------------
| Helper Functions
|--------------------------------------------------------------------------
*/

function setting_escape($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

/**
 * Validate a dynamic SMS URL containing placeholders.
 */
function validate_sms_template_url($url, $requiredPlaceholder = '{NUMBER}')
{
    $url = trim((string)$url);

    if ($url === '') {
        return false;
    }

    if ($requiredPlaceholder !== '' && strpos($url, $requiredPlaceholder) === false) {
        return false;
    }

    // Replace placeholders before validating the URL.
    $validationUrl = str_replace(
        ['{NUMBER}', '{MSG}'],
        ['8252187647', 'TestMessage'],
        $url
    );

    if (!filter_var($validationUrl, FILTER_VALIDATE_URL)) {
        return false;
    }

    $scheme = strtolower((string)parse_url($validationUrl, PHP_URL_SCHEME));

    return in_array($scheme, ['http', 'https'], true);
}

/*
|--------------------------------------------------------------------------
| Current Site Settings
|--------------------------------------------------------------------------
*/

$currentSiteData = site_data();

$currentNewSmsConfig = json_decode(
    (string)($currentSiteData['NewUrlsms'] ?? ''),
    true
);

if (!is_array($currentNewSmsConfig)) {
    $currentNewSmsConfig = [];
}

$currentNewSmsUrl = trim(
    (string)($currentNewSmsConfig['url'] ?? '')
);

/*
|--------------------------------------------------------------------------
| New OTP SMS Service Update
|--------------------------------------------------------------------------
*/

if (
    isset($_POST['newsmsserviceupdate'])
    && (int)$user_data['user_id'] > 0
) {
    $newSmsService = trim(
        (string)($_POST['newSmsService'] ?? 'No')
    );

    $newSmsUrl = trim(
        (string)($_POST['newSmsUrl'] ?? '')
    );

    if (!in_array($newSmsService, ['Yes', 'No'], true)) {
        awal_alert_msg(
            "Please select a valid New SMS Service option!",
            'error'
        );
    } elseif (
        $newSmsService === 'Yes'
        && $newSmsUrl === ''
    ) {
        awal_alert_msg(
            "Please enter the New OTP SMS API URL!",
            'error'
        );
    } elseif (
        $newSmsUrl !== ''
        && strpos($newSmsUrl, '{NUMBER}') === false
    ) {
        awal_alert_msg(
            "New OTP SMS URL must contain {NUMBER} placeholder!",
            'error'
        );
    } elseif (
        $newSmsUrl !== ''
        && !validate_sms_template_url($newSmsUrl, '{NUMBER}')
    ) {
        awal_alert_msg(
            "Please enter a valid New OTP SMS API URL!",
            'error'
        );
    } else {
        /*
         * When service is No and URL is blank,
         * preserve the previously saved URL.
         */
        if ($newSmsService === 'No' && $newSmsUrl === '') {
            $newSmsUrl = $currentNewSmsUrl;
        }

        $newSmsUrlJson = json_encode(
            [
                'url' => $newSmsUrl
            ],
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );

        $insData = [
            'newSmsService' => $newSmsService,
            'NewUrlsms'     => $newSmsUrlJson
        ];

        if (
            db_update(
                "sitedata",
                $insData,
                "user_id='" . (int)$user_data['user_id'] . "'"
            )
        ) {
            awal_alert_msg(
                "New OTP SMS Service Updated Successfully!",
                'success',
                ''
            );
        } else {
            awal_alert_msg(
                "No Any Changes!",
                'info'
            );
        }
    }

    // Reload updated settings.
    $currentSiteData = site_data();

    $currentNewSmsConfig = json_decode(
        (string)($currentSiteData['NewUrlsms'] ?? ''),
        true
    );

    if (!is_array($currentNewSmsConfig)) {
        $currentNewSmsConfig = [];
    }

    $currentNewSmsUrl = trim(
        (string)($currentNewSmsConfig['url'] ?? '')
    );
}

/*
|--------------------------------------------------------------------------
| Old Dynamic SMS API Update
|--------------------------------------------------------------------------
*/

if (
    isset($_POST['smsapiupdate'])
    && (int)$user_data['user_id'] > 0
) {
    $url = trim((string)($_POST['url'] ?? ''));

    if (
        $url !== ''
        && validate_sms_template_url($url, '{NUMBER}')
    ) {
        $smsapi = json_encode(
            [
                "url" => $url
            ],
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );

        $insData = [
            'smsapi' => $smsapi
        ];

        if (
            db_update(
                "sitedata",
                $insData,
                "user_id='" . (int)$user_data['user_id'] . "'"
            )
        ) {
            awal_alert_msg(
                "API Updated Successfully!",
                'success',
                ''
            );
        } else {
            awal_alert_msg(
                "No Any Changes!",
                'info'
            );
        }
    } else {
        awal_alert_msg(
            "Please enter a valid URL containing {NUMBER}!",
            'error'
        );
    }
}

/*
|--------------------------------------------------------------------------
| SMTP Update
|--------------------------------------------------------------------------
*/

if (
    isset($_POST['smtpupdate'])
    && (int)$user_data['user_id'] > 0
) {
    $username = trim(strip_tags((string)($_POST['username'] ?? '')));
    $password = trim((string)($_POST['password'] ?? ''));
    $sender   = trim(strip_tags((string)($_POST['sender'] ?? '')));
    $host     = trim(strip_tags((string)($_POST['host'] ?? '')));
    $port     = trim(strip_tags((string)($_POST['port'] ?? '')));
    $protocol = trim(strip_tags((string)($_POST['protocol'] ?? '')));

    if (
        $username !== ''
        && $password !== ''
        && $sender !== ''
        && $host !== ''
        && $port !== ''
        && in_array($protocol, ['tls', 'ssl'], true)
    ) {
        $smtp = json_encode(
            [
                "username" => $username,
                "password" => $password,
                "sender"   => $sender,
                "host"     => $host,
                "port"     => $port,
                "protocol" => $protocol
            ],
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
        );

        $insData = [
            'smtp' => $smtp
        ];

        if (
            db_update(
                "sitedata",
                $insData,
                "user_id='" . (int)$user_data['user_id'] . "'"
            )
        ) {
            awal_alert_msg(
                "SMTP Updated Successfully!",
                'success',
                ''
            );
        } else {
            awal_alert_msg(
                "No Any Changes!",
                'info'
            );
        }
    } else {
        awal_alert_msg(
            "Please Fill All Valid Details!",
            'error'
        );
    }
}

/*
|--------------------------------------------------------------------------
| Display Values
|--------------------------------------------------------------------------
*/

$currentNewSmsService = trim(
    (string)($currentSiteData['newSmsService'] ?? 'No')
);

if (!in_array($currentNewSmsService, ['Yes', 'No'], true)) {
    $currentNewSmsService = 'No';
}



if ($currentNewSmsUrl === '') {
    $currentNewSmsUrl = $defaultNewSmsUrl;
}
?>

<div class="row">

    <!-- New OTP SMS Service -->
    <div class="col-md-12 mb-3">
        <div class="card text-dark">
            <div class="card-header bg-success text-white py-2">
                <div class="d-flex align-items-center">
                    <span class="mr-auto">
                        <i class="fa fa-mobile-alt mr-1"></i>
                        New OTP SMS Service
                    </span>

                    <?php if ($currentNewSmsService === 'Yes'): ?>
                        <span class="badge badge-light text-success">
                            Active
                        </span>
                    <?php else: ?>
                        <span class="badge badge-light text-danger">
                            Inactive
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="p-3">
                <div class="alert alert-info">
                    <strong>Yes:</strong>
                    Login, Create Account and Forgot Password OTP will use
                    the new Send OTP and Verify OTP API.
                    <br>

                    <strong>No:</strong>
                    The existing old SMS and email system will continue working.
                </div>

                <form class="row text-dark" method="POST" action="">

                    <div class="col-md-4 mb-3">
                        <label for="newSmsService">
                            Enable New OTP SMS Service
                        </label>

                        <select
                            name="newSmsService"
                            id="newSmsService"
                            class="form-control"
                            required
                        >
                            <option
                                value="No"
                                <?= $currentNewSmsService === 'No' ? 'selected' : '' ?>
                            >
                                No — Use Old SMS System
                            </option>

                            <option
                                value="Yes"
                                <?= $currentNewSmsService === 'Yes' ? 'selected' : '' ?>
                            >
                                Yes — Use New OTP API
                            </option>
                        </select>
                    </div>

                    <div class="col-md-8 mb-3">
                        <label for="newSmsUrl">
                            New OTP Send URL — Required placeholder:
                            <strong>{NUMBER}</strong>
                        </label>

                        <input
                            type="text"
                            class="form-control"
                            id="newSmsUrl"
                            name="newSmsUrl"
                            placeholder="https://sms.example.com/api?action=send_otp&apiKey=KEY&mobile={NUMBER}"
                            value="<?= setting_escape($currentNewSmsUrl) ?>"
                            required
                        >

                        <small class="form-text text-muted">
                            The authentication system will use this URL to send
                            OTP. The mobile number will replace
                            <strong>{NUMBER}</strong>.
                        </small>
                    </div>

                    <div class="col-md-4 mb-3">
                        <button
                            type="submit"
                            class="btn btn-success btn-block"
                            name="newsmsserviceupdate"
                        >
                            <i class="fa fa-save mr-1"></i>
                            Save New OTP Settings
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>

    <!-- Existing Dynamic SMS API -->
    <div class="col-md-12 mb-3">
        <div class="card text-danger">
            <div class="card-header bg-primary text-white py-2">
                <div class="d-flex align-items-center">
                    <span class="mr-auto">
                        Old Dynamic SMS API
                    </span>
                </div>
            </div>

            <div class="p-3">
                <form class="row text-dark" method="POST" action="">

                    <div class="col-md-12 mb-3">
                        <label>
                            Dynamic SMS API — {NUMBER} | {MSG}
                        </label>

                        <input
                            type="text"
                            class="form-control"
                            placeholder="https://example.com/send-message?api_key=123456&number={NUMBER}&message={MSG}"
                            name="url"
                            value="<?= setting_escape(smsapi("url")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <button
                            type="submit"
                            class="btn btn-primary btn-block"
                            name="smsapiupdate"
                        >
                            Submit
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>

    <!-- SMTP -->
    <div class="col-md-12 mb-3">
        <div class="card text-danger">
            <div class="card-header bg-primary text-white py-2">
                <div class="d-flex align-items-center">
                    <span class="mr-auto">SMTP</span>
                </div>
            </div>

            <div class="p-3">
                <form class="row text-dark" method="POST" action="">

                    <div class="col-md-4 mb-3">
                        <label>Username</label>

                        <input
                            type="email"
                            class="form-control"
                            placeholder="Enter Username"
                            name="username"
                            value="<?= setting_escape(smtp("username")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Password</label>

                        <input
                            type="password"
                            class="form-control"
                            placeholder="Enter Password"
                            name="password"
                            value="<?= setting_escape(smtp("password")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Sender</label>

                        <input
                            type="text"
                            class="form-control"
                            placeholder="Enter Sender"
                            name="sender"
                            value="<?= setting_escape(smtp("sender")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Host</label>

                        <input
                            type="text"
                            class="form-control"
                            placeholder="Enter Host"
                            name="host"
                            value="<?= setting_escape(smtp("host")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Port</label>

                        <input
                            type="number"
                            class="form-control"
                            placeholder="Enter Port"
                            name="port"
                            min="1"
                            max="65535"
                            value="<?= setting_escape(smtp("port")) ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Protocol</label>

                        <select
                            name="protocol"
                            class="form-control"
                            required
                        >
                            <option
                                value="tls"
                                <?= smtp("protocol") === "tls" ? 'selected' : '' ?>
                            >
                                TLS
                            </option>

                            <option
                                value="ssl"
                                <?= smtp("protocol") === "ssl" ? 'selected' : '' ?>
                            >
                                SSL
                            </option>
                        </select>
                    </div>

                    <div class="col-md-4 mb-3">
                        <button
                            type="submit"
                            class="btn btn-primary btn-block"
                            name="smtpupdate"
                        >
                            Submit
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const serviceSelect = document.getElementById('newSmsService');
    const urlInput = document.getElementById('newSmsUrl');

    function updateNewSmsField() {
        if (!serviceSelect || !urlInput) {
            return;
        }

        if (serviceSelect.value === 'Yes') {
            urlInput.required = true;
            urlInput.disabled = false;
            urlInput.closest('.col-md-8').style.opacity = '1';
        } else {
            urlInput.required = false;
            urlInput.disabled = false;
            urlInput.closest('.col-md-8').style.opacity = '0.75';
        }
    }

    serviceSelect.addEventListener('change', updateNewSmsField);
    updateNewSmsField();
});
</script>

<?php
require_once("../layouts/members/foot.php");
summernote('#noticealert');
?>