<?php include __DIR__ . '/../header.php'; ?>

<?php
use Core\App\Models\ShippingIntegrationModel;
use Core\System\ThemeManager;

/* ==========================================================
   Integrations - Configure Shipping Provider
========================================================== */

// الدولة الحالية
$country = ThemeManager::getSetting('country', 'Algeria');
$isAlgeria = in_array(mb_strtolower(trim($country)), ['algeria', 'dz', 'algérie', 'الجزائر'], true);

// مزودي الشحن (نتركهم كلهم)
$shippingProviders = [
    'ecotrack'   => 'Ecotrack',
    'dhd'        => 'DHD',
    'zr_express' => 'ZR Express',
    'yalidine'   => 'Yalidine',
    'maystro'    => 'Maystro',
];

// provider من الرابط
$providerKey = $_GET['provider'] ?? '';
$providerKey = is_string($providerKey) ? trim($providerKey) : '';

if (!array_key_exists($providerKey, $shippingProviders)) {
    $providerKey = '';
}

$model = new ShippingIntegrationModel();

// القيم الافتراضية
$current = [
    'enabled'   => 0,
    'api_id'    => '',
    'api_token' => '',
];

// تحميل من DB
if ($providerKey !== '') {
    $row = $model->getByProvider($providerKey);
    if (is_array($row)) {
        $current['enabled']   = (int)($row['is_active'] ?? 0);
        $current['api_id']    = (string)($row['api_id'] ?? '');
        $current['api_token'] = (string)($row['api_token'] ?? '');
    }
}

// حفظ
$saved = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if ($providerKey === '') {
        $error = __('integrations.invalid_provider', 'Invalid shipping provider.');
    } elseif (!$isAlgeria) {
        $error = __('integrations.only_algeria_error',
            'Shipping providers are available only when the selected country is Algeria.'
        );
    } else {

        $enabled  = isset($_POST['enabled']) ? 1 : 0;
        $apiId    = trim($_POST['api_id'] ?? '');
        $apiToken = trim($_POST['api_token'] ?? '');

        $model->save(
            $providerKey,
            $shippingProviders[$providerKey],
            $apiId,
            $apiToken,
            $enabled,
            'DZ'
        );

        $saved = true;
        $current['enabled']   = $enabled;
        $current['api_id']    = $apiId;
        $current['api_token'] = $apiToken;
    }
}
?>

<div class="container-fluid py-3">

    <div class="d-flex align-items-center justify-content-between mb-3">
        <h3 class="mb-0">
            <i class="bi bi-truck me-2"></i>
            <?= __('integrations.configure_title', 'Configure Shipping Provider') ?>
        </h3>

        <a href="/admin/integrations" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i>
            <?= __('actions.back', 'Back') ?>
        </a>
    </div>

    <?php if ($saved): ?>
        <div class="alert alert-success">
            <?= __('ui.success', 'Settings saved successfully!') ?>
        </div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="card shadow-sm">
        <div class="card-header">
            <strong><?= htmlspecialchars($shippingProviders[$providerKey] ?? '') ?></strong>
        </div>

        <div class="card-body">

            <form method="POST">
                <?= \Core\System\Csrf::field(); ?>

                <div class="row g-3 mb-4">

                    <div class="col-md-4">
                        <div class="form-check form-switch mt-4">
                            <input class="form-check-input"
                                   type="checkbox"
                                   name="enabled"
                                   <?= $current['enabled'] ? 'checked' : '' ?>>
                            <label class="form-check-label">
                                <?= __('integrations.enabled', 'Enabled') ?>
                            </label>
                        </div>
                    </div>

                </div>

                <!-- ============================= -->
                <!-- YALIDINE -->
                <!-- ============================= -->
                <?php if ($providerKey === 'yalidine'): ?>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">
                                API ID <small class="text-muted">(X-API-ID)</small>
                            </label>
                            <input type="text"
                                   class="form-control"
                                   name="api_id"
                                   value="<?= htmlspecialchars($current['api_id']) ?>"
                                   placeholder="ex: 123456">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">
                                API Token <small class="text-muted">(X-API-TOKEN)</small>
                            </label>
                            <input type="password"
                                   class="form-control"
                                   name="api_token"
                                   value="<?= htmlspecialchars($current['api_token']) ?>">
                        </div>
                    </div>

                <!-- ============================= -->
                <!-- ECOTRACK, DHD & ZR EXPRESS -->
                <!-- ============================= -->
                <?php elseif (in_array($providerKey, ['ecotrack', 'dhd', 'zr_express'], true)): ?>

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">
                                <?= __('integrations.api_id', 'API Base URL') ?>
                            </label>
                            <input type="text"
                                   class="form-control"
                                   name="api_id"
                                   value="<?= htmlspecialchars($current['api_id']) ?>">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">
                                <?= __('integrations.api_token', 'API Token') ?>
                            </label>
                            <input type="password"
                                   class="form-control"
                                   name="api_token"
                                   value="<?= htmlspecialchars($current['api_token']) ?>">
                        </div>
                    </div>

                <!-- ============================= -->
                <!-- MAYSTRO -->
                <!-- ============================= -->
                <?php elseif ($providerKey === 'maystro'): ?>

                    <div class="alert alert-info d-flex gap-2 align-items-start mb-3">
                        <i class="bi bi-info-circle-fill mt-1"></i>
                        <div>
                            <strong>Maystro Delivery (New API)</strong><br>
                            <small>
                                API endpoint: <code>orders-management.maystro-delivery.com/api</code><br>
                                <?= __('integrations.maystro.token_hint', 'You only need your API Token from the Maystro dashboard. Leave the API ID field empty.') ?>
                            </small>
                        </div>
                    </div>

                    <div class="row g-3">

                        <div class="col-md-8">
                            <label class="form-label fw-semibold">
                                <?= __('integrations.api_token', 'API Token') ?>
                                <span class="text-danger">*</span>
                            </label>
                            <div class="input-group">
                                <input type="password"
                                       class="form-control font-monospace"
                                       name="api_token"
                                       id="maystroApiToken"
                                       value="<?= htmlspecialchars($current['api_token']) ?>"
                                       placeholder="<?= __('integrations.maystro.token_placeholder', 'Paste your Maystro API token here...') ?>"
                                       autocomplete="off">
                                <button type="button" class="btn btn-outline-secondary"
                                        onclick="document.getElementById('maystroApiToken').type = (document.getElementById('maystroApiToken').type === 'password') ? 'text' : 'password'">
                                    <i class="bi bi-eye"></i>
                                </button>
                            </div>
                            <div class="form-text text-muted">
                                <?= __('integrations.maystro.where_token', 'Find it in your Maystro dashboard → API Settings') ?>
                            </div>
                        </div>

                        <div class="col-12">
                        <label class="form-label fw-semibold">
                            API Base URL
                            <span class="badge bg-secondary ms-1" style="font-size:10px">optional</span>
                        </label>
                        <input type="text"
                               class="form-control font-monospace"
                               name="api_id"
                               value="<?= htmlspecialchars($current['api_id']) ?>"
                               placeholder="https://orders-management.maystro-delivery.com/api">
                        <div class="form-text text-muted">
                            Leave empty for production.
                            Dev/staging: <code>https://orders-management-dev.maystro-delivery.com/api</code>
                        </div>
                    </div>

                    <div class="col-md-4 d-flex align-items-end">
                            <button type="button" class="btn btn-outline-primary w-100"
                                    onclick="testMaystroConnection()"
                                    id="maystroTestBtn">
                                <i class="bi bi-wifi me-1"></i>
                                <?= __('integrations.test_connection', 'Test Connection') ?>
                            </button>
                        </div>

                    </div>

                    <div id="maystroTestResult" class="mt-3" style="display:none"></div>

                    <script>
                    function testMaystroConnection() {
                        const token = document.getElementById('maystroApiToken').value.trim();
                        const btn   = document.getElementById('maystroTestBtn');
                        const result = document.getElementById('maystroTestResult');

                        if (!token) {
                            result.innerHTML = '<div class="alert alert-warning py-2"><i class="bi bi-exclamation-triangle me-1"></i><?= __('integrations.maystro.enter_token_first', 'Please enter the API token first.') ?></div>';
                            result.style.display = 'block';
                            return;
                        }

                        btn.disabled = true;
                        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span><?= __('integrations.testing', 'Testing...') ?>';
                        result.style.display = 'none';

                        fetch('/admin/integrations/maystro/test-connection', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                _csrf: document.querySelector('input[name="_csrf"]')?.value || '',
                                api_token: token
                            }),
                            credentials: 'same-origin'
                        })
                        .then(r => r.json())
                        .then(res => {
                            if (res.success) {
                                result.innerHTML = '<div class="alert alert-success py-2"><i class="bi bi-check-circle me-1"></i>' + (res.message || '<?= __('integrations.connection_ok', 'Connection successful!') ?>') + '</div>';
                            } else {
                                result.innerHTML = '<div class="alert alert-danger py-2"><i class="bi bi-x-circle me-1"></i>' + (res.message || res.error || '<?= __('integrations.connection_failed', 'Connection failed.') ?>') + '</div>';
                            }
                            result.style.display = 'block';
                        })
                        .catch(e => {
                            result.innerHTML = '<div class="alert alert-danger py-2"><i class="bi bi-x-circle me-1"></i>' + e.message + '</div>';
                            result.style.display = 'block';
                        })
                        .finally(() => {
                            btn.disabled = false;
                            btn.innerHTML = '<i class="bi bi-wifi me-1"></i><?= __('integrations.test_connection', 'Test Connection') ?>';
                        });
                    }
                    </script>

                <!-- ============================= -->
                <!-- OTHER PROVIDERS (NOT READY YET) -->
                <!-- ============================= -->
                <?php else: ?>

                    <div class="alert alert-info mb-0">
                        <?= __('integrations.not_ready',
                            'This shipping provider will be available in a future update.'
                        ) ?>
                    </div>

                <?php endif; ?>

                <hr class="my-4">

                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save me-1"></i>
                    <?= __('actions.save', 'Save') ?>
                </button>

            </form>

        </div>
    </div>

</div>

<?php include __DIR__ . '/../footer.php'; ?>