<?php

namespace Core\App\Controllers;

use Core\App\Models\OrderModel;
use Core\App\Models\ShippingIntegrationModel;
use Core\App\Services\OrderShippingService;
use Core\App\Services\BulkShippingService;
use Core\App\Support\ShippingSettings;

/**
 * BulkOrderController
 *
 * Standalone controller for bulk shipping confirmation.
 * Does NOT modify any existing order confirmation routes or logic.
 */
class BulkOrderController
{
    private BulkShippingService $bulkService;

    public function __construct()
    {
        $this->requireAuth();
        $orders              = new OrderModel();
        $shippingService     = new OrderShippingService($orders);
        $this->bulkService   = new BulkShippingService($orders, $shippingService);
    }

    /* =====================================================================
       Auth
    ===================================================================== */

    private function requireAuth(): void
    {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_SESSION['admin_id'])) {
            header('Location: /admin/login');
            exit;
        }
    }

    private function checkCsrf(): bool
    {
        $token = $_POST['_csrf'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        return $token !== ''
            && !empty($_SESSION['_csrf'])
            && hash_equals((string)$_SESSION['_csrf'], trim($token));
    }

    /* =====================================================================
       GET /admin/orders/bulk-confirm
    ===================================================================== */

    public function index(): void
    {
        $eligibleOrders = $this->bulkService->getEligibleOrders();

        // Active integrations for provider dropdown
        $allIntegrations = (new ShippingIntegrationModel())->getAllIndexed();
        $activeProviders = [];
        foreach ($allIntegrations as $key => $integration) {
            if (!empty($integration['is_active']) && !empty($integration['api_token'])) {
                $activeProviders[$key] = $integration['display_name'] ?: $key;
            }
        }

        // Shipping settings
        $shippingSettings = ShippingSettings::load();
        $selectionMode    = $shippingSettings['provider_selection_mode'] ?? 'manual_admin';
        $forcedProvider   = $shippingSettings['forced_provider'] ?? '';

        require __DIR__ . '/../../../admin/templates/orders/bulk_confirm.php';
    }

    /* =====================================================================
       POST /admin/orders/bulk-confirm/process
    ===================================================================== */

    public function process(): void
    {
        header('Content-Type: application/json; charset=utf-8');

        if (!$this->checkCsrf()) {
            http_response_code(403);
            echo json_encode(['success' => false, 'error' => 'invalid_csrf']);
            return;
        }

        $rawIds   = $_POST['order_ids'] ?? [];
        $provider = trim((string)($_POST['provider'] ?? ''));

        if (!is_array($rawIds) || empty($rawIds)) {
            http_response_code(422);
            echo json_encode(['success' => false,
                'error' => __('bulk_confirm.no_orders_selected', 'No orders selected')]);
            return;
        }

        if ($provider === '') {
            http_response_code(422);
            echo json_encode(['success' => false,
                'error' => __('bulk_confirm.no_provider', 'No provider selected')]);
            return;
        }

        $orderIds = array_values(
            array_filter(array_map('intval', $rawIds), fn($id) => $id > 0)
        );

        try {
            $result = $this->bulkService->processOrders($orderIds, $provider);
            echo json_encode(['success' => true, 'result' => $result]);
        } catch (\Throwable $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
}
