<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Redirect LiveChat dinamis
|--------------------------------------------------------------------------
| Footer cukup mengarah ke:
|
|     livechat.php
|
| Nomor LiveChat dibaca dari tabel help_settings:
|
|     setting_key = livechat_license_id
|
| Opsional:
|
|     setting_key = livechat_url_override
|
| Jika livechat_url_override berisi URL direct.lc.chat yang valid,
| URL tersebut diprioritaskan.
|--------------------------------------------------------------------------
*/

$bootstrapFile = __DIR__ . '/bootstrap.php';

if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

/*
|--------------------------------------------------------------------------
| Koneksi database
|--------------------------------------------------------------------------
*/

$databaseFile = __DIR__ . '/config/database.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (!is_file($databaseFile)) {
        header('Location: bantuan.php?chat=unavailable');
        exit;
    }

    require_once $databaseFile;
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    header('Location: bantuan.php?chat=unavailable');
    exit;
}

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

$pdo->setAttribute(
    PDO::ATTR_DEFAULT_FETCH_MODE,
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| Default
|--------------------------------------------------------------------------
*/

$liveChatLicenseId = '';
$liveChatOverride = '';

try {
    $statement = $pdo->query(
        "SELECT
            setting_key,
            setting_value
         FROM help_settings
         WHERE setting_key IN (
            'livechat_license_id',
            'livechat_url_override'
         )
         AND is_active = 1"
    );

    foreach ($statement->fetchAll() as $row) {
        $settingKey = trim(
            (string) (
                $row['setting_key'] ??
                ''
            )
        );

        $settingValue = trim(
            (string) (
                $row['setting_value'] ??
                ''
            )
        );

        if ($settingKey === 'livechat_license_id') {
            $liveChatLicenseId = preg_replace(
                '/[^0-9]/',
                '',
                $settingValue
            );
        }

        if ($settingKey === 'livechat_url_override') {
            $liveChatOverride = $settingValue;
        }
    }
} catch (Throwable $exception) {
    error_log(
        'LIVECHAT REDIRECT ERROR: ' .
        $exception->getMessage()
    );

    header('Location: bantuan.php?chat=unavailable');
    exit;
}

/*
|--------------------------------------------------------------------------
| Validasi URL override
|--------------------------------------------------------------------------
| Hanya izinkan HTTPS dan host direct.lc.chat.
|--------------------------------------------------------------------------
*/

if ($liveChatOverride !== '') {
    $overrideParts = parse_url(
        $liveChatOverride
    );

    $overrideScheme = strtolower(
        (string) (
            $overrideParts['scheme'] ??
            ''
        )
    );

    $overrideHost = strtolower(
        (string) (
            $overrideParts['host'] ??
            ''
        )
    );

    if (
        $overrideScheme === 'https' &&
        $overrideHost === 'direct.lc.chat'
    ) {
        header(
            'Location: ' .
            $liveChatOverride,
            true,
            302
        );
        exit;
    }
}

/*
|--------------------------------------------------------------------------
| Validasi nomor LiveChat
|--------------------------------------------------------------------------
*/

if (
    $liveChatLicenseId === '' ||
    preg_match(
        '/^[0-9]{5,20}$/',
        $liveChatLicenseId
    ) !== 1
) {
    header('Location: bantuan.php?chat=unavailable');
    exit;
}

/*
|--------------------------------------------------------------------------
| Redirect langsung ke LiveChat
|--------------------------------------------------------------------------
*/

$liveChatUrl =
    'https://direct.lc.chat/' .
    rawurlencode($liveChatLicenseId) .
    '/';

header(
    'Location: ' .
    $liveChatUrl,
    true,
    302
);

exit;
