<?php

namespace Core\App\Controllers;

use Core\App\Models\ShippingIntegrationModel;
use Core\App\Models\Settings;
use Core\App\Cron\CronRunner;
use Core\App\Cron\Tasks\UpdateShippingStatusTask;


class ShippingControlController
{
    protected ShippingIntegrationModel $integrationModel;

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

    /**
     * =============================
     * Control Center Page
     * URL: /admin/shipments/control
     * =============================
     */
    public function index()
    {
        // Load integrations (DB only)
        $integrations = $this->integrationModel->getAllIndexed();

        // Load CRON settings
        $settingsModel = new Settings();
        $settings = $settingsModel->getAll();

        $cronEnabled = (int)($settings['cron_enabled'] ?? 0);
        $cronToken   = $settings['cron_token'] ?? null;

        require ROOT_PATH . '/admin/templates/header.php';
        require ROOT_PATH . '/admin/templates/shipping/control.php';
        require ROOT_PATH . '/admin/templates/footer.php';
    }

    /**
     * =============================
     * Run Shipping Update NOW
     * AJAX
     * URL: /admin/shipments/control/run
     * =============================
     */
    public function runNow()
    {
        header('Content-Type: application/json');

        try {
            $runner = new CronRunner();
            $runner->register(new UpdateShippingStatusTask());

            $results = $runner->runAll();

            echo json_encode([
                'success' => true,
                'executed_at' => date('Y-m-d H:i:s'),
                'results' => $results
            ]);
        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
        exit;
    }

    /**
     * =============================
     * Toggle Provider Status
     * AJAX
     * URL: /admin/shipments/control/toggle
     * =============================
     */
    public function toggleProvider()
    {
        header('Content-Type: application/json');

        $provider = $_POST['provider'] ?? null;

        if (!$provider) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error'   => 'PROVIDER_REQUIRED'
            ]);
            exit;
        }

        $this->integrationModel->toggle($provider);

        echo json_encode([
            'success' => true
        ]);
        exit;
    }
}
