<?php
// admin/product_notice.php
// Temporary dev: show errors (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$__errors = [];
$__notices = [];

try {
    require_once __DIR__ . '/../config.php';
} catch (Throwable $e) {
    $__errors[] = "Could not load config.php: " . $e->getMessage();
}

// Optional guards from your app
if (function_exists('require_admin')) {
    try { require_admin(); } catch (Throwable $e) { $__errors[] = "require_admin() failed: " . $e->getMessage(); }
}
if (function_exists('require_login')) {
    try { require_login(); } catch (Throwable $e) { /* ignore if admin already checked */ }
}

// Ensure $pdo exists
if (!isset($pdo)) {
    $__errors[] = "Database connection \$pdo is not set. Make sure config.php defines \$pdo (PDO).";
}

// AJAX: fetch subcategory notice
if (isset($_GET['action']) && $_GET['action'] === 'fetch' && isset($_GET['id'])) {
    header('Content-Type: application/json; charset=utf-8');
    $out = ['ok' => false, 'data' => null, 'err' => null];
    try {
        if (!isset($pdo)) { throw new Exception("No PDO."); }
        $id = (int)$_GET['id'];
        $stmt = $pdo->prepare("SELECT sc.id, sc.name, sc.notice_text, sc.notice_enabled, s.name AS service_name
                               FROM subcategories sc
                               JOIN services s ON s.id = sc.service_id
                               WHERE sc.id=?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) { $out['ok'] = true; $out['data'] = $row; }
    } catch (Throwable $e) {
        $out['err'] = $e->getMessage();
    }
    echo json_encode($out);
    exit;
}

// Handle POST: save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Optional CSRF verify
    if (function_exists('verify_csrf')) {
        try { verify_csrf(); } catch (Throwable $e) { $__errors[] = "CSRF failed: " . $e->getMessage(); }
    }

    $subcat_id = (int)($_POST['subcategory_id'] ?? 0);
    $notice_text = trim($_POST['notice_text'] ?? '');
    $notice_enabled = isset($_POST['notice_enabled']) ? 1 : 0;

    if ($subcat_id <= 0) {
        $__errors[] = "Please select a subcategory.";
    } else {
        try {
            if (!isset($pdo)) { throw new Exception("No PDO."); }
            $stmt = $pdo->prepare("UPDATE subcategories SET notice_text=?, notice_enabled=? WHERE id=?");
            $stmt->execute([$notice_text, $notice_enabled, $subcat_id]);
            $__notices[] = "Notice saved successfully.";
            // Redirect using app helper if exists
            if (function_exists('redirect')) {
                redirect('product_notice.php?highlight=' . $subcat_id);
                exit;
            }
        } catch (Throwable $e) {
            $__errors[] = "DB update failed: " . $e->getMessage();
        }
    }
}

// Load subcategories
$subs = [];
try {
    if (isset($pdo)) {
        $q = "SELECT sc.id, sc.name, sc.notice_enabled, sc.notice_text, s.name AS service_name
              FROM subcategories sc
              JOIN services s ON s.id = sc.service_id
              ORDER BY s.name ASC, sc.name ASC";
        $subs = $pdo->query($q)->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $__errors[] = "Load subcategories failed: " . $e->getMessage();
}

// Group for optgroup
$groups = [];
foreach ($subs as $row) {
    $groups[$row['service_name']][] = $row;
}

// Optional admin header/footer
$__used_header = false;
try { require __DIR__ . '/header.php'; $__used_header = true; } catch (Throwable $e) { /* fallback bare html */ }

if (!$__used_header):
?><!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Product Notice</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head><body class="bg-light">
<div class="container py-3">
<?php endif; ?>

<!-- Messages -->
<?php if (!empty($__errors)): ?>
  <div class="alert alert-danger"><strong>Errors:</strong><ul class="mb-0">
    <?php foreach ($__errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?>
  </ul></div>
<?php endif; ?>
<?php if (!empty($__notices)): ?>
  <div class="alert alert-success"><ul class="mb-0">
    <?php foreach ($__notices as $n): ?><li><?php echo htmlspecialchars($n); ?></li><?php endforeach; ?>
  </ul></div>
<?php endif; ?>
<?php if (function_exists('show_flash')) { show_flash(); } ?>

<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
    <li class="breadcrumb-item active" aria-current="page">Product Notice</li>
  </ol>
</nav>

<h3 class="mb-3"><i class="bi bi-megaphone-fill"></i> Product Notice Manager</h3>

<div class="row g-4">
  <div class="col-lg-5">
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">
        <strong>Set / Update Notice</strong>
      </div>
      <div class="card-body">
        <form method="post" id="noticeForm">
          <?php if (function_exists('csrf_field')) { csrf_field(); } ?>
          <div class="mb-3">
            <label class="form-label">Select Subcategory</label>
            <select name="subcategory_id" id="subcategory_id" class="form-select" required>
              <option value="">-- Choose --</option>
              <?php foreach ($groups as $service => $items): ?>
                <optgroup label="<?php echo htmlspecialchars($service); ?>">
                <?php foreach ($items as $it): ?>
                  <option value="<?php echo (int)$it['id']; ?>"
                    <?php if ((int)($_GET['highlight'] ?? 0) === (int)$it['id']) echo 'selected'; ?>>
                    <?php echo htmlspecialchars($it['name']); ?>
                    <?php if (!empty($it['notice_enabled']) && !empty($it['notice_text'])): ?>
                      (has notice)
                    <?php endif; ?>
                  </option>
                <?php endforeach; ?>
                </optgroup>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Pick a subcategory to load its current notice.</div>
          </div>

          <div class="form-check mb-3">
            <input type="checkbox" class="form-check-input" id="notice_enabled" name="notice_enabled" value="1">
            <label class="form-check-label" for="notice_enabled">Enable notice</label>
          </div>

          <div class="mb-3">
            <label class="form-label">Notice Text</label>
            <textarea name="notice_text" id="notice_text" rows="6" class="form-control" placeholder="Write notice..."></textarea>
          </div>

          <button type="submit" class="btn btn-primary">
            <i class="bi bi-save"></i> Save Notice
          </button>
        </form>
      </div>
    </div>
  </div>

  <div class="col-lg-7">
    <div class="card shadow-sm">
      <div class="card-header bg-light">
        <strong>Current Notices</strong>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover align-middle">
            <thead class="table-light">
              <tr>
                <th>ID</th>
                <th>Service</th>
                <th>Subcategory</th>
                <th>Enabled</th>
                <th>Preview</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($subs as $row): $enabled = (int)$row['notice_enabled'] === 1; ?>
              <tr <?php if ((int)($_GET['highlight'] ?? 0) === (int)$row['id']) echo 'class="table-success"'; ?>>
                <td><?php echo (int)$row['id']; ?></td>
                <td><?php echo htmlspecialchars($row['service_name'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($row['name'] ?? ''); ?></td>
                <td><?php echo $enabled ? '<span class="badge bg-success">On</span>' : '<span class="badge bg-secondary">Off</span>'; ?></td>
                <td style="max-width:280px;">
                  <?php
                    $prev = trim((string)($row['notice_text'] ?? ''));
                    echo $prev ? htmlspecialchars(mb_strimwidth($prev, 0, 120, '…', 'UTF-8')) : '<span class="text-muted">—</span>';
                  ?>
                </td>
                <td><a class="btn btn-sm btn-outline-primary" href="product_notice.php?highlight=<?php echo (int)$row['id']; ?>">Edit</a></td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
document.getElementById('subcategory_id').addEventListener('change', async function() {
  const id = this.value;
  const enabled = document.getElementById('notice_enabled');
  const text = document.getElementById('notice_text');
  if (!id) { enabled.checked=false; text.value=''; return; }
  try {
    const res = await fetch('product_notice.php?action=fetch&id=' + encodeURIComponent(id));
    const json = await res.json();
    if (json.ok && json.data) {
      enabled.checked = json.data.notice_enabled == 1;
      text.value = json.data.notice_text || '';
    } else { enabled.checked=false; text.value=''; }
  } catch (e) { enabled.checked=false; text.value=''; }
});

window.addEventListener('DOMContentLoaded', function() {
  const sel = document.getElementById('subcategory_id');
  if (sel && sel.value) sel.dispatchEvent(new Event('change'));
});
</script>

<?php
$__used_footer = false;
try { require __DIR__ . '/footer.php'; $__used_footer = true; } catch (Throwable $e) { /* bare footer */ }
if (!$__used_footer): ?>
</div><!-- /.container -->
</body></html>
<?php endif; ?>
