<?php

namespace Core\App\Controllers;

use Core\App\Models\ShippingIntegrationModel;

class IntegrationsController
{
    protected ShippingIntegrationModel $model;

    protected array $providers = [
        'ecotrack'   => 'Ecotrack',
        'dhd'        => 'DHD',
        'zr_express' => 'ZR Express',
        'yalidine'   => 'Yalidine',
        'maystro'    => 'Maystro',
    ];

    public function __construct()
    {
        $this->model = new ShippingIntegrationModel();
    }

    /* =============================
       ADMIN — Integrations Index
    ============================= */
    public function index()
    {
        $providers = $this->providers;
        $stored    = $this->model->getAllIndexed();

        // Load tracking integrations indexed by provider
        $trackingStored = [];
        try {
            $stmt = \db()->query("SELECT provider, is_active FROM tracking_integrations");
            foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
                $trackingStored[$row['provider']] = (int)$row['is_active'];
            }
        } catch (\Throwable $e) {
            // tracking_integrations table may not exist on older installations
        }

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/integrations/index.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =============================
       ADMIN — Configure Provider
    ============================= */
    public function configure()
    {
        $provider = $_GET['provider'] ?? '';
        $provider = is_string($provider) ? trim($provider) : '';

        if ($provider === '' || !array_key_exists($provider, $this->providers)) {
            http_response_code(404);
            echo 'Invalid integration provider.';
            exit;
        }

        $integration = $this->model->getByProvider($provider);

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/integrations/configure.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /* =============================
       ADMIN — Save Configuration
    ============================= */
    public function save()
    {
        $provider = $_GET['provider'] ?? '';
        $provider = is_string($provider) ? trim($provider) : '';

        if ($provider === '' || !array_key_exists($provider, $this->providers)) {
            header('Location: /admin/integrations');
            exit;
        }

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

        $this->model->saveOrUpdate([
            'provider'  => $provider,
            'api_id'    => trim($apiId),
            'api_token' => trim($apiToken),
            'enabled'   => $enabled,
        ]);

        header('Location: /admin/integrations');
        exit;
    }

    /* =============================
       ADMIN — Toggle Enable / Disable
    ============================= */
    public function toggle()
    {
        \Core\System\Csrf::check();

        $provider = $_POST['provider'] ?? $_GET['provider'] ?? '';
        $provider = is_string($provider) ? trim($provider) : '';

        if ($provider !== '' && array_key_exists($provider, $this->providers)) {
            $this->model->toggleStatus($provider);
        }

        header('Location: /admin/integrations');
        exit;
    }

    /* =============================
       AJAX — Maystro Test Connection
       POST /admin/integrations/maystro/test-connection
    ============================= */
    public function maystroTestConnection()
    {
        header('Content-Type: application/json; charset=utf-8');

        $body     = json_decode(file_get_contents('php://input'), true) ?? [];
        $apiToken = trim((string)($body['api_token'] ?? ''));

        // Fallback: use saved token from DB
        if ($apiToken === '') {
            $savedIntegration = $this->model->getByProvider('maystro');
            $apiToken         = trim((string)($savedIntegration['api_token'] ?? ''));
        }

        if ($apiToken === '') {
            echo json_encode([
                'success' => false,
                'message' => __('integrations.maystro.enter_token_first', 'Please enter the API token first.'),
            ]);
            return;
        }

        try {
            // Support dev URL override from saved api_id field
            $savedIntegration = $savedIntegration ?? $this->model->getByProvider('maystro') ?? [];
            $baseUrl          = trim((string)($savedIntegration['api_id'] ?? ''));

            $client   = new \Core\App\Integrations\Shipping\MaystroClient($apiToken, $baseUrl);
            $response = $client->testConnection();

            if (!empty($response['success'])) {
                $data  = $response['data'] ?? [];
                $count = is_array($data) ? count($data) : '?';
                echo json_encode([
                    'success' => true,
                    'message' => __('integrations.connection_ok', 'Connection successful!')
                               . ' (' . $count . ' wilayas loaded)',
                ]);
            } else {
                $errDetail = $response['error'] ?? ('HTTP ' . ($response['status'] ?? '?'));
                echo json_encode([
                    'success' => false,
                    'message' => __('integrations.connection_failed', 'Connection failed.') . ' ' . $errDetail,
                ]);
            }
        } catch (\Throwable $e) {
            echo json_encode([
                'success' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }
}
