<?php
// api/next_best_time.php
declare(strict_types=1);

header("Content-Type: application/json; charset=utf-8");

function out(array $payload, int $code=200): void {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  exit;
}

$schedule = require __DIR__ . "/schedule_map.php";

$region = trim((string)($_GET["region"] ?? "US"));
$type   = strtolower(trim((string)($_GET["type"] ?? "post"))); // post|reel|bts

if (!isset($schedule["regions"][$region])) {
  out(["ok"=>false, "error"=>"Unknown region"], 400);
}

$regionCfg = $schedule["regions"][$region];
$tzName = (string)$regionCfg["timezone"];

$timeKey = $type === "reel" ? "reel_time" : ($type === "bts" ? "bts_time" : "post_time");
$timeStr = (string)($regionCfg[$timeKey] ?? "12:00");

$rules = $schedule["rules"];
$days = $type === "reel" ? ($rules["reels_days"] ?? []) : ($type === "bts" ? ($rules["bts_days"] ?? []) : ($rules["posts_days"] ?? []));
if (!is_array($days) || !count($days)) out(["ok"=>false,"error"=>"No days configured"], 500);

// map "mon".."sun" to ISO-8601 numeric day-of-week (1=Mon..7=Sun)
$map = ["mon"=>1,"tue"=>2,"wed"=>3,"thu"=>4,"fri"=>5,"sat"=>6,"sun"=>7];
$targetDow = [];
foreach ($days as $d) {
  $d = strtolower(trim((string)$d));
  if (isset($map[$d])) $targetDow[] = $map[$d];
}
$targetDow = array_values(array_unique($targetDow));
sort($targetDow);
if (!count($targetDow)) out(["ok"=>false,"error"=>"Invalid days configured"], 500);

try {
  $tz = new DateTimeZone($tzName);
} catch (Throwable $e) {
  out(["ok"=>false,"error"=>"Bad timezone"], 500);
}

$nowLocal = new DateTimeImmutable("now", $tz);

// parse time "HH:MM"
if (!preg_match('/^(\d{1,2}):(\d{2})$/', $timeStr, $m)) out(["ok"=>false,"error"=>"Bad time format"], 500);
$hh = (int)$m[1];
$mm = (int)$m[2];

// Find the next occurrence among the allowed days at that local time
$best = null;

for ($i=0; $i<=14; $i++) {
  $candidateDate = $nowLocal->modify("+{$i} days")->setTime($hh, $mm, 0);
  $dow = (int)$candidateDate->format("N"); // 1..7
  if (!in_array($dow, $targetDow, true)) continue;

  // Must be in the future (or at least 60s ahead to avoid immediate-fire edge cases)
  if ($candidateDate->getTimestamp() <= ($nowLocal->getTimestamp() + 60)) continue;

  $best = $candidateDate;
  break;
}

if (!$best) {
  out(["ok"=>false, "error"=>"Could not find next slot"], 500);
}

$bestUtc = $best->setTimezone(new DateTimeZone("UTC"));
$bestET  = $best->setTimezone(new DateTimeZone("America/New_York"));

out([
  "ok" => true,
  "region" => $region,
  "timezone" => $tzName,
  "type" => $type,
  "platforms" => $schedule["platforms"],
  "next" => [
    "local" => $best->format(DateTimeInterface::ATOM),
    "utc"   => $bestUtc->format(DateTimeInterface::ATOM),
    "et"    => $bestET->format(DateTimeInterface::ATOM),
    "human" => $best->format("D, M j, Y g:i A") . " (" . $tzName . ")",
  ],
]);
