<?php

namespace App\Services;


use Illuminate\Support\Facades\Http;


class AppleService
{
    // Simple verifyReceipt approach (production). Use sandbox endpoint for testing.
    // public function verifyReceipt(string $receipt)
    // {
        // $endpoint = 'https://buy.itunes.apple.com/verifyReceipt';
        // $response = Http::post($endpoint, [
        //     'receipt-data' => $receipt,
        //     'password' => config('services.apple.shared_secret'),
        //     'exclude-old-transactions' => true,
        // ]);


        // return $response->json();
        public function verifyReceipt(string $receipt)
    {
        $productionUrl = 'https://buy.itunes.apple.com/verifyReceipt';
        $sandboxUrl    = 'https://sandbox.itunes.apple.com/verifyReceipt';

        $payload = [
            'receipt-data' => $receipt,
            'password' => config('services.apple.shared_secret'),
            'exclude-old-transactions' => true,
        ];

        // جرّب Production
        $response = Http::post($productionUrl, $payload);
        $data = $response->json();

        // لو receipt بتاع sandbox
        if (isset($data['status']) && $data['status'] == 21007) {
            $response = Http::post($sandboxUrl, $payload);
            $data = $response->json();
        }

        return $data;
    }
    // }
}
