<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\BbtApiModel;

class PullSubDealPartsAPI extends Controller
{
    public function index()
    {
        // Prepare our local model
        $model = new BbtApiModel();

        // 1. Get the highest local ID from bbt_subdeal_parts
        $maxLocalId = $model->getMaxSubdealPartsId();

        // 2. Calculate the start ID as maxLocalId - 700 (but not below 0)
        $startId = $maxLocalId - 700;
        if ($startId < 0) {
            $startId = 0;
        }

        // 3. Define how many rows we want per chunk
        $chunkSize = 100;

        // 4. Keep requesting data until we get an empty response
        while (true) {
            // a) Calculate this chunk's end ID (e.g., startId..startId+99)
            $endId = $startId + $chunkSize - 1;

            // b) Make the remote request for ONLY that ID range
            $client = \Config\Services::curlrequest();
            $response = $client->request('GET', 'https://brechbilltools.com/index.php/admin/WillisPlaygroundAPI/getSubdealPartsDataByIdRange', [
                'headers' => [
                    'X-API-KEY' => 'hK9g8D1jS0aWx3QzhK9g8D1jS0aWx3Qz',
                ],
                'query' => [
                    'start_id' => $startId,
                    'end_id'   => $endId,
                ],
            ]);

            // c) Decode the JSON
            $chunkData = json_decode($response->getBody(), true);

            // d) If the returned data is empty, we're done
            if (empty($chunkData)) {
                break;
            }

            // e) Upsert the chunk into the local DB
            $model->upsertSubdealParts($chunkData);

            // f) Move to the next chunk
            $startId = $endId + 1;
        }

        // 5. Finally, return a JSON response
        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'SubdealParts data synced successfully using the last 700 ID logic.',
        ]);
    }
}
