<?php
require_once __DIR__ . '/../global.php';

$tw = new TwilioWhatsApp();

$cap = 60;

$sentLastMin = (int) $dbF->getRow("SELECT COUNT(*) AS c FROM whatsapp_messages WHERE direction = 'outbound' AND created_at >= (NOW() - INTERVAL 60 SECOND)")['c'];

$budget = max(0, $cap - $sentLastMin);
if ($budget <= 0) {
  echo "No budget; cron exit\n";
  return;
}

$jobs = $dbF->getRows("SELECT * FROM wa_queue WHERE status = 'queued' AND (schedule_at IS NULL OR schedule_at <= NOW()) ORDER BY id ASC LIMIT {$budget}");

foreach ($jobs as $row) {
  $opt = $dbF->getRow("SELECT opt_out FROM whatsapp_contacts WHERE phone_e164 = ? LIMIT 1", [$row['to_e164']]);
  if ($opt && (int) $opt['opt_out'] === 1) {
    $dbF->setRow("UPDATE wa_queue SET status = 'failed', error_msg = 'opt_out' WHERE id = ?", [$row['id']]);
    continue;
  }

  $lastIn = $dbF->getRow("SELECT MAX(created_at) AS last_in FROM whatsapp_messages WHERE direction = 'inbound' 
  AND (wa_from = CONCAT('whatsapp:', ?) OR wa_to = CONCAT('whatsapp:', ?))", [$row['to_e164'], $row['to_e164']]);

  $within24h = (!empty($lastIn['last_in']) && (time() - strtotime($lastIn['last_in']) <= 24 * 3600));
  if (!$within24h) {
    $dbF->setRow("UPDATE wa_queue SET status = 'failed', error_msg = 'outside_24h_window' WHERE id = ?", [$row['id']]);
    continue;
  }

  try {
    $resp = $tw->send($row['to_e164'], $row['rendered_body'], $row['media_url'] ?: null);
    $sid = is_array($resp) ? ($resp['sid'] ?? null) : null;

    $dbF->setRow("UPDATE wa_queue SET status = 'sent', twilio_sid = ? WHERE id = ?", [$sid, $row['id']]);

    $acc = $dbF->getRow("SELECT account_id FROM whatsapp_contacts WHERE phone_e164 = ? LIMIT 1", [$row['to_e164']]);
    $accId = $acc['account_id'] ?? null;

    $dbF->setRow("INSERT INTO whatsapp_messages (account_id, direction, wa_from, wa_to, body, media_url, status, twilio_sid) 
    VALUES (?, 'outbound', ?, ?, ?, ?, 'sent', ?)", [$accId, TWILIO_WHATSAPP_FROM, 'whatsapp:' . $row['to_e164'], $row['rendered_body'], ($row['media_url'] ?: null), $sid]);

    $dbF->setRow("INSERT INTO wa_audit (queue_id, event, payload) VALUES (?, 'sent', ?)", [$row['id'], json_encode($resp)]);
  } catch (Exception $e) {
    $dbF->setRow("UPDATE wa_queue SET status = 'failed', error_msg = ? WHERE id = ?", [$e->getMessage(), $row['id']]);
    $dbF->setRow("INSERT INTO wa_audit (queue_id, event, payload) VALUES (?, 'send_error', ?)", [$row['id'], json_encode(['error' => $e->getMessage()])]);
  }
}

echo "Cron Ran Successfully";