<?php
// fetch-bootswatch.php — download all Bootswatch themes locally
$version = '5.3.7';
$themes = [
  'brite','cerulean','cosmo','cyborg','darkly','flatly','journal','litera','lumen','lux',
  'materia','minty','morph','pulse','quartz','sandstone','simplex','sketchy','slate',
  'solar','spacelab','superhero','united','vapor','yeti','zephyr'
];

// Where to store (adjust if you like)
$baseDir = __DIR__ . '/assets/bootswatch';

function ensure_dir($path) {
  if (!is_dir($path)) {
    if (!mkdir($path, 0777, true) && !is_dir($path)) {
      throw new RuntimeException("Failed to create directory: $path");
    }
  }
}

function download($url, $dest) {
  // Use curl if available for better error reporting
  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_CONNECTTIMEOUT => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_USERAGENT => 'BootswatchFetcher/1.0',
    ]);
    $data = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    if ($data === false || $code >= 400) {
      throw new RuntimeException("HTTP $code fetching $url. $err");
    }
    if (file_put_contents($dest, $data) === false) {
      throw new RuntimeException("Cannot write file: $dest");
    }
    return;
  }
  // Fallback to file_get_contents
  $data = @file_get_contents($url);
  if ($data === false) {
    $e = error_get_last();
    throw new RuntimeException("Failed to get $url. " . ($e['message'] ?? ''));
  }
  if (file_put_contents($dest, $data) === false) {
    throw new RuntimeException("Cannot write file: $dest");
  }
}

echo "Bootswatch $version → $baseDir\n";
ensure_dir($baseDir);

foreach ($themes as $code) {
  $dir = "$baseDir/$code";
  ensure_dir($dir);
  $url = "https://cdn.jsdelivr.net/npm/bootswatch@$version/dist/$code/bootstrap.min.css";
  $file = "$dir/bootstrap.min.css";
  try {
    download($url, $file);
    echo "✓ $code\n";
  } catch (Throwable $t) {
    echo "✗ $code — {$t->getMessage()}\n";
  }
}

echo "Done.\n";
