<?php
$api_key   = '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';
$model     = 'gpt-4o';
$data_dir  = __DIR__ . '/data';
$image_dir = __DIR__ . '/images';
$signs_dir = __DIR__ . '/signs';

foreach ([$data_dir, $image_dir, $signs_dir] as $d) {
    if (!file_exists($d)) mkdir($d, 0777, true);
}

function openai_post(string $url, array $payload, string $key): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $key
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload)
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code === 200 && $resp) ? ['ok'=>true,'body'=>json_decode($resp,true)] : ['ok'=>false,'err'=>"API error $code: $resp"];
}

function save_remote_image(string $url, string $dir, string $slug): string {
    $file = "$dir/{$slug}.png";
    $image_data = @file_get_contents($url);
    if ($image_data === false) return $url;
    if (!file_exists($file)) {
        file_put_contents($file, $image_data);
    }
    return '/images/' . basename($file);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $birth_date  = $_POST['birth_date']  ?? '';
    $birth_time  = $_POST['birth_time']  ?? '';
    $birth_place = $_POST['birth_place'] ?? '';
    $div_date    = $_POST['div_date']    ?? '';
    $div_time    = $_POST['div_time']    ?? '';
    $div_place   = $_POST['div_place']   ?? '';
    $language    = $_POST['language']    ?? '';
    $output_lang = $_POST['output_lang'] ?? '';

    if (!$birth_date || !$birth_place || !$div_date || !$div_place || !$language || !$output_lang) {
        exit("<div style='color:red;'>All fields are required.</div>");
    }

    $start = date('F j, Y', strtotime($div_date));
    $end   = date('F j, Y', strtotime($div_date . ' +7 days'));
    $birth_time_display = $birth_time ? " at $birth_time" : "";
    $div_time_display = $div_time ? " at $div_time" : "";

    $user_message = "Please create an astrological reading for someone with the following details:\n\nBirth Information:\n- Born on $birth_date$birth_time_display in $birth_place\n\nDivination Request:\n- Reading requested for $div_date$div_time_display in $div_place\n- Sign name should be in: $language\n- Full response should be in: $output_lang\n\nPlease provide a complete astrological profile using the specified format.";

    $format_instructions = "Respond using this exact format, no JSON, no markdown, no explanation:\n\nSign Name: \nImage Prompt: \nTraits:\n  Behavioral: (at least 100 words)\n  Relational: (at least 100 words)\n  Temporal: (at least 100 words)\nCharacter Type:\n  Aspect: (at least 100 words)\n  Perspective: (at least 100 words)\n  Viscosity: (at least 100 words)\nDrink Sensation:\n  Flavour Symbol: \n  Tone: \n  Form: \nWeekly Divination:\n  (for the week of $start to $end)\n  Provide at least 300 words. Use poetic and rigorous language.\nContributors:\n  [credit info]";

    $chat_resp = openai_post('https://api.openai.com/v1/chat/completions', [
        'model' => $model,
        'messages' => [
            ['role' => 'system', 'content' => 'You are an expert astrologer and divination specialist.'],
            ['role' => 'user', 'content' => $user_message],
            ['role' => 'assistant', 'content' => 'Understood. Format?'],
            ['role' => 'user', 'content' => $format_instructions]
        ]
    ], $api_key);

    if (!$chat_resp['ok']) {
        exit("<div style='color:red;'>" . $chat_resp['err'] . "</div>");
    }

    $text = $chat_resp['body']['choices'][0]['message']['content'] ?? '';
    preg_match('/Sign Name:\s*(.+)/', $text, $m);
    $sign_name = trim($m[1] ?? 'unknown');
    $slug = preg_replace('/[^a-z0-9]+/i', '_', strtolower($sign_name));

    preg_match('/Aspect:\s*(.+?)\s*Perspective:/s', $text, $m1);
    preg_match('/Perspective:\s*(.+?)\s*Viscosity:/s', $text, $m2);
    preg_match('/Viscosity:\s*(.+?)\s*Drink Sensation:/s', $text, $m3);
    $aspect = trim($m1[1] ?? '');
    $perspect = trim($m2[1] ?? '');
    $viscosity = trim($m3[1] ?? '');

    $img_prompt = "a simple shape. without words or patterns. only 5 flat polygons max. Generate an abstract simple geometric shape. a greyscale expressive geometric vertices. The geometry by no more than 3 polygons. The geometry should make a single visual sign. A geometric interpertation from qualities of '{$aspect}', '{$perspect}', and '{$viscosity}'. a simple unified shaped geometry. Without text appearing anywhere";

    $img_resp = openai_post('https://api.openai.com/v1/images/generations', [
        'model' => 'dall-e-3',
        'prompt' => $img_prompt,
        'n' => 1,
        'size' => '1024x1024',
        'response_format' => 'url'
    ], $api_key);

    $image_url = '';
    if ($img_resp['ok']) {
        $remote = $img_resp['body']['data'][0]['url'] ?? '';
        $image_url = save_remote_image($remote, $image_dir, $slug);
    }

$public_url = "https://aaooo.ee/dazodiola/signs/{$slug}.html";
$qr_svg = '<img src="https://quickchart.io/qr?text=' . urlencode($public_url) . '&size=150" alt="QR Code">';

// $image_path = '/dazodiola/' . ltrim($image_url, '/');  // ensures single slash
$image_path = 'https://aaooo.ee/dazodiola/' . $image_url;


    $html_file = "$signs_dir/{$slug}.html";
    $html_output = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{$sign_name}</title>
    <link rel="stylesheet" href="https://aaooo.ee/dazodiola/stylee.css">
    <style>
       img { max-width: 300px; display: block; margin: 2em auto; }
    pre { white-space: pre-wrap; background: #f3f3f3; padding: 1em; border-radius: 8px; }
    .section { margin-bottom: 2em; text-align: center; }
    .qr-caption { font-style: italic; color: #555; margin-top: 0.5em; font-size: 0.9em; }
    </style>
</head>
<body>

<div class="nav-container">
  <button class="nav-toggle" onclick="toggleNav()">Divee<br>Astro<br>Zodioli</button>
  <nav id="mainNav">
    <a href="#">About</a>
    <a href="#">Download</a>
    <a href="#">Dazodioli Signs & Divinations</a>
    <a href="#">Contact</a>
  </nav>
</div>

<script>
function toggleNav() {
  const nav = document.getElementById('mainNav');
  nav.classList.toggle('show');
}
</script>


  <h1>{$sign_name}</h1>
  <div class="section">
HTML;
$html_output .= '<img src="' . htmlspecialchars($image_path) . '" alt="Generated Symbol" class="symbol-image">';

$html_output .= <<<HTML
  </div>
  <div class="section">
    <h2>Full Response</h2>
    <pre>{$text}</pre>
  </div>
  <div class="section">
    <h2>Your Sign's QRcode</h2>
    {$qr_svg}
    <div class="qr-caption">{$public_url}</div>
  </div>
</body>
</html>
HTML;

    file_put_contents($html_file, $html_output);
    header("Location: signs/{$slug}.html");
    exit;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Diveee Astro Zodilogy</title>
  <link rel="stylesheet" href="stylee.css">
</head>
<style>
    .flashy {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: repeating-linear-gradient(
    to bottom,
    #ff3333 0%, #ff3333 16.6%,
    #ff1a1a 16.6%, #ff1a1a 33.2%,
    #e60000 33.2%, #e60000 49.8%,
    #b30000 49.8%, #b30000 66.4%,
    #800000 66.4%, #800000 83%,
    #4d0000 83%, #4d0000 100%
  );
  z-index: 9999;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

@keyframes flashText {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

</style>
<script>
document.querySelector('form').addEventListener('submit', function() {
  document.getElementById('flashy-overlay').style.display = 'flex';
});
</script>
<body>
<div class="nav-container">
  <button class="nav-toggle" onclick="toggleNav()">Divee<br>Astro<br>Zodioli</button>
  <nav id="mainNav">
    <a href="#">About</a>
    <a href="#">Download</a>
    <a href="#">Dazodioli Signs & Divinations</a>
    <a href="#">Contact</a>
  </nav>
</div>

<form method="post">
  <div class="main-fields">
    <fieldset>
      <legend>Birth Info</legend>
      <div class="field-row">
        <div class="field-group">
          <label>Date:</label>
          <input type="date" name="birth_date" required>
        </div>
        <div class="field-group">
          <label>Time:</label>
          <input type="time" name="birth_time">
        </div>
        <div class="field-group">
          <label>Place:</label>
          <input type="text" name="birth_place" required>
        </div>
      </div>
    </fieldset>

    <fieldset>
      <legend>Divination</legend>
      <div class="field-row">
        <div class="field-group">
          <label>Date:</label>
          <input type="date" name="div_date" required>
        </div>
        <div class="field-group">
          <label>Time:</label>
          <input type="time" name="div_time">
        </div>
        <div class="field-group">
          <label>Place:</label>
          <input type="text" name="div_place" required>
        </div>
      </div>
    </fieldset>
  </div>

  <div class="language-card">
    <legend>Language choices</legend>
    <div class="language-fields">
      <div>
        <label>The new DAZodiolic sign-name language?</label>
        <input type="text" name="language" required>
      </div>
      <div>
        <label>Your DAZodiolical divination language?</label>
        <input type="text" name="output_lang" required>
      </div>
    </div>
  </div>

  <button type="submit">Lets do DAZodioli</button>
</form>

<div id="flashy-overlay" class="flashy" style="display:none;">
  <div style="text-align:center; padding:2em;">
    <h1 style="animation: flashText 1s infinite;">Hooray!<br>
      Your DAZodiological divination gets assembled.<br>
      Try patience, or let your mind go off on a flashy wander.
    </h1>
    <p style="margin-top:2em;">Apologies if server times out:<br>
    Please - press back, then retry the bottom button.

.</p>
  </div>
</div>


<script>
function toggleNav() {
  const nav = document.getElementById('mainNav');
  nav.classList.toggle('show');
}
</script>
</body>
</html>