<?php

use Simulador\Tables\Cotacao;
use Simulador\Database\DBCotacao;
use Simulador\Database\DBIndicador;

$response = ['success' => true];

try {
    
  $query = "SELECT * FROM indicacoes WHERE id_moskit IS NULL ORDER BY id DESC LIMIT 100";

  $stmt = DBIndicador::get()->prepare($query);
  if ($stmt !== false) {

    $stmt->execute();
    $result = $stmt->get_result();
    if ($result !== false) {
      $data = $result->fetch_all(MYSQLI_ASSOC);
      
      $response['count'] = $result->num_rows;
      
      foreach ($data as $item) {
        $id = $item['id_simulacao'];
        
        $stmt = DBCotacao::get()->prepare("SELECT * FROM cotacoes WHERE id = ?");
        if ($stmt !== false) {
          $stmt->bind_param('i', $id);
          $stmt->execute();
          
          $result = $stmt->get_result();
          if ($result !== false) {
            /** @var string[] $row */
            $row = $result->fetch_assoc();
            $row['id_proposta'] = $row['id'];
            // ksort($row);
            
            $client = new GuzzleHttp\Client();
            $res = $client->request('POST', 'https://dashboard.parceirosproteauto.com.br/api/v1/moskit/deal.php', [
              'json' => $row,
            ]);
            $row['deal'] = json_decode($res->getBody()->getContents());
            $response['data'][] = $row;
          }
        }
      }
    }
  }
} catch (Exception $e) {
  $response['success'] = false;
  $response['message'] = ucfirst($e->getMessage());
}

echo json_encode($response, JSON_PRETTY_PRINT);
