<?php
require __DIR__ . '/auth.php';
requireLogin();

$pdo = db();
$notice = '';

$uploadDir = __DIR__ . '/../uploads';
$siteRoot = rtrim(dirname(dirname($_SERVER['PHP_SELF'])), '/'); // .../admin/notifications.php -> parent of admin/
$uploadUrlBase = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https://' : 'http://')
    . $_SERVER['HTTP_HOST'] . $siteRoot . '/uploads/';

function handleImageUpload($uploadDir, $uploadUrlBase) {
    if (empty($_FILES['image']['name']) || $_FILES['image']['error'] === UPLOAD_ERR_NO_FILE) {
        return null; // no file chosen — not an error
    }
    if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Image upload failed (error code ' . $_FILES['image']['error'] . ').');
    }
    if ($_FILES['image']['size'] > 5 * 1024 * 1024) {
        throw new Exception('Image is too large (5MB max).');
    }
    $allowed = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp'];
    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    if (!isset($allowed[$ext])) {
        throw new Exception('Unsupported image type. Use JPG, PNG, GIF, or WEBP.');
    }
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
    $filename = bin2hex(random_bytes(8)) . '.' . $ext;
    if (!move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . '/' . $filename)) {
        throw new Exception('Could not save the uploaded image.');
    }
    return $uploadUrlBase . $filename;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    checkCsrf();
    $action = $_POST['action'] ?? '';

    if ($action === 'send') {
        $title = trim($_POST['title'] ?? '');
        $body  = trim($_POST['body'] ?? '');
        $link  = trim($_POST['link'] ?? '');
        $imageUrlInput = trim($_POST['image_url'] ?? '');
        $type  = in_array($_POST['type'] ?? '', ['promo', 'announcement'], true) ? $_POST['type'] : 'promo';
        $accent = $type === 'announcement' ? '#60a5fa' : '#6dc82c';
        $targetRaw = $_POST['target_license_id'] ?? '';
        $targetLicenseId = ($targetRaw === '' || $targetRaw === 'all') ? null : (int) $targetRaw;

        try {
            $uploadedUrl = handleImageUpload($uploadDir, $uploadUrlBase);
            $imageUrl = $uploadedUrl ?: ($imageUrlInput ?: null);

            if ($title === '' || $body === '') {
                $notice = 'Title and message are required.';
            } else {
                $stmt = $pdo->prepare(
                    'INSERT INTO notifications (title, body, type, link, image_url, accent_color, target_license_id) VALUES (?, ?, ?, ?, ?, ?, ?)'
                );
                $stmt->execute([$title, $body, $type, $link ?: null, $imageUrl, $accent, $targetLicenseId]);
                $notice = $targetLicenseId
                    ? 'Notification sent to that customer.'
                    : 'Notification sent to all customers.';
            }
        } catch (Exception $e) {
            $notice = $e->getMessage();
        }
    }

    if ($action === 'delete' && !empty($_POST['id'])) {
        $stmt = $pdo->prepare('DELETE FROM notifications WHERE id = ?');
        $stmt->execute([$_POST['id']]);
        $notice = 'Notification deleted (devices that already saw it are unaffected).';
    }
}

$licenses = $pdo->query(
    "SELECT id, license_key, customer_name, customer_email FROM licenses ORDER BY created_at DESC"
)->fetchAll();

$sent = $pdo->query(
    "SELECT n.*, l.customer_name, l.customer_email, l.license_key
     FROM notifications n
     LEFT JOIN licenses l ON l.id = n.target_license_id
     ORDER BY n.created_at DESC"
)->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notifications — License Admin</title>
<style>
  :root{--brand:#6dc82c;--bg:#0f1115;--card:#171a21;--card2:#12141a;--border:#262b36;--text:#e7e9ee;--text2:#9aa3b2;--red:#f87171;--amber:#fbbf24;--blue:#60a5fa;}
  *{box-sizing:border-box;}
  body{margin:0;background:var(--bg);color:var(--text);font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;font-size:14px;}
  header{display:flex;align-items:center;justify-content:space-between;padding:18px 28px;border-bottom:1px solid var(--border);background:var(--card2);}
  header h1{font-size:16px;margin:0;}
  nav{display:flex;gap:18px;align-items:center;}
  nav a{color:var(--text2);text-decoration:none;font-size:13px;}
  nav a.active{color:var(--text);font-weight:600;}
  nav a:hover{color:var(--text);}
  main{max-width:1100px;margin:0 auto;padding:28px;}
  .notice{background:rgba(109,200,44,.12);border:1px solid rgba(109,200,44,.35);color:var(--brand);padding:10px 14px;border-radius:8px;margin-bottom:20px;}
  .card{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:20px;margin-bottom:24px;}
  .card h2{font-size:14px;margin:0 0 16px;text-transform:uppercase;letter-spacing:.04em;color:var(--text2);}
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px 16px;}
  label{display:block;font-size:11px;color:var(--text2);margin-bottom:5px;font-weight:600;text-transform:uppercase;letter-spacing:.03em;}
  input[type=text],input[type=url],select,textarea{width:100%;padding:9px 10px;border-radius:7px;border:1px solid var(--border);background:#0d0f14;color:var(--text);font-size:13px;font-family:inherit;}
  input:focus,textarea:focus,select:focus{outline:none;border-color:var(--brand);}
  .full{grid-column:1/-1;}
  .hint{color:var(--text2);font-size:11px;margin-top:4px;}
  button, .btn{border:0;border-radius:7px;padding:8px 14px;font-weight:600;font-size:12px;cursor:pointer;}
  .btn-primary{background:var(--brand);color:#0b1200;}
  .btn-primary:hover{filter:brightness(1.08);}
  .btn-danger{background:transparent;border:1px solid rgba(248,113,113,.4);color:var(--red);}
  .btn-danger:hover{background:rgba(248,113,113,.1);}
  table{width:100%;border-collapse:collapse;}
  th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.03em;color:var(--text2);padding:8px 10px;border-bottom:1px solid var(--border);}
  td{padding:10px;border-bottom:1px solid var(--border);vertical-align:top;font-size:13px;}
  tr:last-child td{border-bottom:none;}
  .badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:11px;font-weight:700;}
  .badge-promo{background:rgba(109,200,44,.15);color:var(--brand);}
  .badge-announcement{background:rgba(96,165,250,.15);color:var(--blue);}
  .muted{color:var(--text2);font-size:12px;}
  form.inline{display:inline;}
</style>
</head>
<body>
<header>
  <h1>License Admin</h1>
  <nav>
    <a href="index.php">Licenses</a>
    <a href="notifications.php" class="active">Notifications</a>
    <a href="logout.php">Logout</a>
  </nav>
</header>
<main>

  <?php if ($notice): ?><div class="notice"><?= e($notice) ?></div><?php endif; ?>

  <div class="card">
    <h2>Send Notification</h2>
    <p class="muted" style="margin-top:-8px;margin-bottom:16px;">
      License-expiry warnings are sent automatically — this form is for promos and announcements.
      Delivered as a popup inside the desktop app next time it checks in (usually within 30 minutes).
    </p>
    <form method="post" enctype="multipart/form-data">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="send">
      <div class="grid">
        <div>
          <label>Type</label>
          <select name="type">
            <option value="promo">Promo</option>
            <option value="announcement">Announcement</option>
          </select>
        </div>
        <div>
          <label>Send To</label>
          <select name="target_license_id">
            <option value="all">All customers</option>
            <?php foreach ($licenses as $lic): ?>
              <option value="<?= (int) $lic['id'] ?>">
                <?= e($lic['customer_name'] ?: $lic['license_key']) ?><?= $lic['customer_email'] ? ' · ' . e($lic['customer_email']) : '' ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="full">
          <label>Title</label>
          <input type="text" name="title" placeholder="e.g. 30% off renewal this week" required>
        </div>
        <div class="full">
          <label>Message</label>
          <textarea name="body" rows="3" placeholder="Shown below the title in the popup" required></textarea>
        </div>
        <div class="full">
          <label>Link (optional)</label>
          <input type="url" name="link" placeholder="https://... (adds a Check It Out button)">
        </div>
        <div>
          <label>Image (optional)</label>
          <input type="file" name="image" accept=".jpg,.jpeg,.png,.gif,.webp,image/*">
          <div class="hint">JPG/PNG/GIF/WEBP, 5MB max. Uploading a file overrides the URL below.</div>
        </div>
        <div>
          <label>...or Image URL</label>
          <input type="url" name="image_url" placeholder="https://example.com/promo.png">
        </div>
      </div>
      <br>
      <button class="btn-primary" type="submit">Send Notification</button>
    </form>
  </div>

  <div class="card">
    <h2>Sent (<?= count($sent) ?>)</h2>
    <table>
      <thead>
        <tr>
          <th>Message</th>
          <th>Type</th>
          <th>Target</th>
          <th>Seen by</th>
          <th>Sent</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($sent as $n): ?>
        <tr>
          <td>
            <?php if (!empty($n['image_url'])): ?>
              <img src="<?= e($n['image_url']) ?>" alt="" style="width:44px;height:44px;object-fit:cover;border-radius:6px;display:block;margin-bottom:6px;">
            <?php endif; ?>
            <div><?= e($n['title']) ?></div>
            <div class="muted"><?= e($n['body']) ?></div>
          </td>
          <td><span class="badge badge-<?= e($n['type']) ?>"><?= e(ucfirst($n['type'])) ?></span></td>
          <td class="muted"><?= $n['target_license_id'] ? e($n['customer_name'] ?: $n['license_key']) : 'All customers' ?></td>
          <td class="muted"><?= notificationReadCount($n['id']) ?> device(s)</td>
          <td class="muted"><?= e($n['created_at']) ?></td>
          <td>
            <form class="inline" method="post" onsubmit="return confirm('Delete this notification? Devices that already saw it keep it dismissed.');">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="delete">
              <input type="hidden" name="id" value="<?= (int) $n['id'] ?>">
              <button class="btn-danger" type="submit">Delete</button>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (!$sent): ?>
          <tr><td colspan="6" class="muted">No notifications sent yet.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

</main>
</body>
</html>
