<?php

namespace Core\App\Controllers\Admin;

use Core\App\Models\ShippingIntegrationModel;

class EcotrackController
{
    public function deleteOrder()
    {
        $tracking = $_POST['tracking'] ?? null;

        if (!$tracking) {
            return $this->json([
                'success' => false,
                'message' => __('ecotrack.missing_tracking')
            ]);
        }

        $integration = (new ShippingIntegrationModel())->getByProvider('ecotrack');

        if (!$integration || empty($integration['is_active'])) {
            return $this->json([
                'success' => false,
                'message' => __('ecotrack.not_active')
            ]);
        }

        $url = rtrim($integration['api_id'], '/') .
               '/api/v1/delete/order?tracking=' . urlencode($tracking);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => 'DELETE',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $integration['api_token'],
                'Accept: application/json'
            ]
        ]);

        $res = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($res, true);

        if (!empty($data['success'])) {
            return $this->json([
                'success' => true,
                'message' => __('ecotrack.delete_success')
            ]);
        }

        return $this->json([
            'success' => false,
            'message' => $data['message'] ?? __('ecotrack.delete_failed'),
            'error_code' => $data['error'] ?? null
        ]);
    }

    private function json(array $data)
    {
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }
}
