<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Services\ShippoService;
use App\Models\ShippingZone;

class ShippingController extends Controller
{
    // protected $shippoService;
    
    // public function __construct(ShippoService $shippoService)
    // {
    //     $this->shippoService = $shippoService;
    // }

    // public function calculateRates(Request $request)
    // {
    //     $request->validate([
    //         'state' => 'required|string|size:2',
    //     ]);

    //     $state = strtoupper($request->state);
        
    //     // Find the zone for this state
    //     $zone = ShippingZone::where('is_active', true)
    //         ->whereJsonContains('states', $state)
    //         ->first();

    //     // If no specific zone found, use the 'other' zone
    //     if (!$zone) {
    //         $zone = ShippingZone::where('code', 'other')->first();
    //     }

    //     $rates = $zone->rates()
    //         ->where('is_active', true)
    //         ->get()
    //         ->map(function($rate) {
    //             return [
    //                 'service' => $rate->service,
    //                 'service_name' => $rate->service_name,
    //                 'amount' => number_format($rate->amount, 2),
    //                 'days' => $rate->delivery_days
    //             ];
    //         });

    //     return response()->json([
    //         'success' => true,
    //         'rates' => $rates
    //     ]);
    // }


    public function getZonesAndRates(Request $request)
    {
        // Get all active zones with their states
        $zones = ShippingZone::where('is_active', true)->get()
            ->mapWithKeys(function ($zone) {
                return [$zone->code => $zone->states];
            });

        // Get all active rates grouped by zone code
        $rates = ShippingZone::where('is_active', true)->with(['rates' => function ($query) {
            $query->where('is_active', true);
        }])->get()->mapWithKeys(function ($zone) {
            return [$zone->code => $zone->rates->map(function ($rate) {
                return [
                    'service' => $rate->service,
                    'service_name' => $rate->service_name,
                    'amount' => number_format($rate->amount, 2),
                    'days' => $rate->delivery_days
                ];
            })];
        });

        return response()->json([
            'success' => true,
            'zones' => $zones,
            'rates' => $rates
        ]);
    }

    // public function calculateRates(Request $request)
    // {
    //     try {
    //         // Log the incoming request data
    //         Log::info('Shipping calculation request:', $request->all());
            
    //         // Check if we're in local environment or if we should use dummy data
    //         if (app()->environment('local') || config('services.shippo.use_dummy_data', true)) {
    //             // Return dummy shipping rates for testing
    //             return response()->json($this->shippoService->getDummyRates());
    //         }

    //         // Set default weight if not provided
    //         $weight = $request->input('weight', 1.0); // Default to 1 lb if not specified
            
    //         // Prepare address data
    //         $fromAddress = [
    //             'name' => 'Aphrodaily Store',
    //             'street1' => '123 Main Street',
    //             'city' => 'Los Angeles',
    //             'state' => 'CA',
    //             'zip' => '90001',
    //             'country' => 'US',
    //         ];
            
    //         $toAddress = [
    //             'name' => $request->input('name', 'Customer'),
    //             'street1' => $request->address,
    //             'city' => $request->city,
    //             'state' => $request->state,
    //             'zip' => $request->zip_code,
    //             'country' => 'US',
    //         ];
            
    //         $parcel = [
    //             'length' => '10',
    //             'width' => '10',
    //             'height' => '10',
    //             'distance_unit' => 'in',
    //             'weight' => (string) $weight,
    //             'mass_unit' => 'lb',
    //         ];
            
    //         // Get rates from Shippo service
    //         $result = $this->shippoService->getRates($fromAddress, $toAddress, $parcel);
            
    //         return response()->json($result);

    //     } catch (\Exception $e) {
    //         Log::error('Shipping calculation error:', [
    //             'message' => $e->getMessage(),
    //             'trace' => $e->getTraceAsString()
    //         ]);
            
    //         // Return dummy rates if there's an error
    //         return response()->json($this->shippoService->getDummyRates());
    //     }
    // }
}