<?php

namespace App\Controllers;

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

class PullOrdersAPI extends Controller
{
    public function index()
    {
        // 1. Prepare our model
        $model = new BbtApiModel();

        // 2. Find the highest local ID in bbt_orders
        //    (Make sure you've added getMaxOrdersId() in your BbtApiModel)
        $maxLocalId = $model->getMaxOrdersId();

        // 3. Calculate our start ID as "highest local ID - 700" (but not below 0)
        $startId = $maxLocalId - 700;
        if ($startId < 0) {
            $startId = 0;
        }

        // 4. Define our chunk size
        $chunkSize = 100;

        // 5. Loop until no more data is returned
        while (true) {
            // a) Calculate the endId for this chunk
            $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/getOrdersDataByIdRange', [
                'headers' => [
                    'X-API-KEY' => 'hK9g8D1jS0aWx3QzhK9g8D1jS0aWx3Qz',
                ],
                'query' => [
                    'start_id' => $startId,
                    'end_id'   => $endId,
                ],
            ]);

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

            // d) If no data is returned, we still need to delete local rows in this range
            if (empty($chunkData)) {
                // This means everything in [startId..endId] no longer exists at the source
                // Make sure you've created a deleteMissingOrders() method in BbtApiModel
                $model->deleteMissingOrders($startId, $endId, []);
                // Once we've cleaned up, we can break the loop
                break;
            }

            // e) Insert/Update this chunk into our local database
            // Make sure you've created an upsertOrders() method in BbtApiModel
            $model->upsertOrders($chunkData);

            // e2) Delete any rows in the local table that fall within [startId..endId]
            //     but are not present in the chunk data
            $idsInChunk = array_column($chunkData, 'id');
            $model->deleteMissingOrders($startId, $endId, $idsInChunk);

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

        // 6. Return JSON response indicating success
        return $this->response->setJSON([
            'status'  => 'success',
            'message' => "Orders data synced from ID range [{$maxLocalId}-700 ... up to latest] successfully",
        ]);
    }
}
