<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use CodeIgniter\HTTP\CURLRequest;
use Config\Services;

class AreaGeoSeeder extends Seeder
{
    /**
     * API configuration for fetching zones data
     * Configure in .env: AREAGEO_API_URL=https://services-summit.my.id/api/zones
     */
    protected string $apiUrl = 'http://services-summit.my.id/api/zones';

    // public function run()
    // {
    //   // Fetch data from external API
    //   $options = [
    //     'baseURI' => $this->apiUrl,
    //     'timeout' => 30,
    //   ];

    //   // $client = new CURLRequest($options);
    //   $client = Services::curlrequest([
    //       'baseURI' => $this->apiUrl,
    //       'timeout' => 30,
    //   ]);

    //   $response = $client->get('');

    //   if ($response->getStatusCode() !== 200) {
    //     echo "Failed to fetch data from API. Status: " . $response->getStatusCode() . "\n";
    //     return;
    //   }

    //   $externalData = $response->getJSON(true);

    //   if (empty($externalData)) {
    //     echo "No data found from API.\n";
    //     return;
    //   }

    //   // Prepare data for insertion (exclude AreaGeoID to allow auto-increment)
    //   $data = [];
    //   foreach ($externalData as $row) {
    //     $data[] = [
    //       'AreaCode' => $row['zonecode'] ?? null,
    //       'Class' => $row['zoneclass'] ?? null,
    //       'AreaName' => str_replace('_', ' ', $row['zonename'] ?? ''),
    //       'Parent' => $row['parentzoneid'] ?? null,
    //     ];
    //   }

    //   // Insert into local database
    //   $this->db->table('areageo')->insertBatch($data);

    //   echo "Successfully seeded " . count($data) . " area geo records.\n";
    // }
    public function run()
    {
        // Get API URL from environment or use default (HTTP for production)
        $this->apiUrl = env('AREAGEO_API_URL', $this->apiUrl);
        
        $client = Services::curlrequest([
            'baseURI' => $this->apiUrl,
            'timeout' => 30,
            'verify' => str_starts_with($this->apiUrl, 'https://'),
        ]);

        $response = $client->get('');

        if ($response->getStatusCode() !== 200) {
            echo "HTTP Error: {$response->getStatusCode()}" . PHP_EOL;
            return;
        }

        $payload = json_decode($response->getBody(), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            echo "Invalid JSON response: " . json_last_error_msg() . PHP_EOL;
            return;
        }

        if (
            !isset($payload['status'], $payload['data']) ||
            $payload['status'] !== 'success'
        ) {
            echo "Unexpected API structure." . PHP_EOL;
            return;
        }

        $zones = $payload['data'];

        if (empty($zones)) {
            echo "No zone data found." . PHP_EOL;
            return;
        }

        $data = [];
        foreach ($zones as $row) {
            $data[] = [
                'AreaCode' => $row['zonecode'] ?? null,
                'Class' => $row['zoneclass'] ?? null,
                'AreaName' => str_replace('_', ' ', $row['zonename'] ?? ''),
                'Parent' => $row['parentzoneid'],
            ];
        }

        $this->db->table('areageo')->insertBatch($data);

        echo "Seeded " . count($data) . " records." . PHP_EOL;
    }
}
