<?php session_start();
require 'config.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

function normalizePublishedAt($value) {
  $raw = trim((string)$value);
  if ($raw === '') {
    return null;
  }

  $formats = [
    'Y-m-d\\TH:i',
    'Y-m-d\\TH:i:s',
    'Y-m-d H:i:s',
    'Y-m-d H:i',
    'd-m-Y H:i:s',
    'd-m-Y H:i',
    'd-m-Y',
    'Y-m-d'
  ];

  foreach ($formats as $format) {
    $dt = DateTime::createFromFormat($format, $raw);
    if ($dt !== false) {
      return $dt->format('Y-m-d H:i:s');
    }
  }

  $ts = strtotime($raw);
  if ($ts !== false) {
    return date('Y-m-d H:i:s', $ts);
  }

  return null;
}

function normalizeTextField($value, $maxLength = null) {
  $text = trim((string)$value);

  if ($text === '') {
    return null;
  }

  if ($maxLength !== null && $maxLength > 0) {
    if (function_exists('mb_substr')) {
      $text = mb_substr($text, 0, $maxLength);
    } else {
      $text = substr($text, 0, $maxLength);
    }
  }

  return $text;
}

$id = $_GET['id'] ?? null;
if (!$id) {
    exit('No article ID provided');
}

$stmt = $dbh->prepare("SELECT * FROM articles WHERE id = ?");
if (!$stmt) { exit('Database error'); }
$stmt->execute([$id]);
$article = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$article || !is_array($article)) {
  exit('Article not found');
}

$selectedCategory = $_POST['category'] ?? ($article['category'] ?? '');
$categoryStmt = $dbh->query("SELECT DISTINCT category FROM articles WHERE category IS NOT NULL AND TRIM(category) <> '' ORDER BY category ASC");
$categoryOptions = $categoryStmt ? $categoryStmt->fetchAll(PDO::FETCH_COLUMN) : [];
if (empty($categoryOptions)) {
  $categoryOptions = ['Latest', 'News', 'Analysis', 'Education', 'Brokers', 'Tools'];
}

// Normalize published_at to a valid datetime-local value (YYYY-MM-DDTHH:MM) or empty
$published_at_val = '';
if (!empty($article['published_at'])) {
  $raw = trim($article['published_at']);
  $dt = false;

  // Try ISO / strtotime first
  $dt = date_create($raw);

  // If that fails, try common custom formats
  if ($dt === false) {
    $formats = ["d-m-Y H:i:s","d-m-Y H:i","d-m-Y","Y-m-d H:i:s","Y-m-d H:i","Y-m-d"];
    foreach ($formats as $fmt) {
      $try = DateTime::createFromFormat($fmt, $raw);
      if ($try !== false) { $dt = $try; break; }
    }
  }

  if ($dt !== false) {
    // Ensure minutes are present; if not, set to 00
    $published_at_val = $dt->format('Y-m-d\\TH:i');
  } else {
    // Couldn't parse -> leave empty to avoid invalid datetime-local value
    $published_at_val = '';
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title = normalizeTextField($_POST['title'] ?? '', 255);
  $summary = normalizeTextField($_POST['summary'] ?? '');
  $category = normalizeTextField($_POST['category'] ?? '', 50);
  $image_url = normalizeTextField($_POST['image_url'] ?? '', 255);
  $article_url = normalizeTextField($_POST['article_url'] ?? '', 255);
  $published_at = normalizePublishedAt($_POST['published_at'] ?? null);

  if ($title === null || $category === null) {
    die('Title and category are required.');
  }

  try {
    $stmt = $dbh->prepare("UPDATE articles SET title = ?, summary = ?, category = ?, image_url = ?, article_url = ?, published_at = ? WHERE id = ?");
    $stmt->execute([$title, $summary, $category, $image_url, $article_url, $published_at, $id]);
  } catch (Throwable $e) {
    die('Article update failed: ' . htmlspecialchars($e->getMessage()));
  }

    header('Location: articles_list.php');
    exit;
}
?>
<?php include "includes/header.php"; include "includes/sidebar.php"; ?>

<style>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');
/* Use admin theme variables so dark/light toggle works */
body {
  background:
    radial-gradient(circle at top left, rgba(245, 197, 24, 0.08), transparent 24%),
    linear-gradient(180deg, var(--dark-900) 0%, var(--dark-800) 100%);
  font-family: 'Plus Jakarta Sans', sans-serif;
  color: var(--text-1);
  margin: 0;
  padding: 0;
}

.admin-main-content {
  margin-left: var(--sw, 260px);
  padding: 92px 40px 40px;
  transition: all 0.3s ease;
}

.edit-card {
  max-width: 1040px;
  margin: 0 auto;
  background: linear-gradient(180deg, var(--dark-700), var(--dark-800));
  border-radius: 22px;
  padding: 32px;
  box-shadow: 0 24px 60px rgba(0, 0, 0, 0.28);
  border: 1px solid rgba(255, 255, 255, 0.05);
  position: relative;
  overflow: hidden;
}

.edit-card::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(135deg, rgba(245, 197, 24, 0.06), transparent 40%, rgba(76, 168, 245, 0.03));
  pointer-events: none;
}

.edit-header {
  position: relative;
  z-index: 1;
  font-family: 'Playfair Display', serif;
  font-size: 30px;
  color: var(--text-1);
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.edit-header::after {
  content: 'Update article content and metadata';
  display: block;
  margin-top: 8px;
  font-family: 'Plus Jakarta Sans', sans-serif;
  font-size: 13px;
  font-weight: 500;
  color: var(--text-2);
}

.edit-form {
  position: relative;
  z-index: 1;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 18px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 18px;
}

label {
  color: var(--text-2);
  font-weight: 700;
  font-size: 13px;
  letter-spacing: 0.02em;
}

input[type="text"],
input[type="datetime-local"],
textarea,
select {
  width: 100%;
  background: var(--dark-600);
  color: var(--text-1);
  border: 1px solid rgba(255, 255, 255, 0.06);
  padding: 13px 14px;
  border-radius: 12px;
  font-size: 15px;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease, background 0.2s ease;
}

select {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}

textarea {
  min-height: 150px;
  resize: vertical;
  line-height: 1.55;
}

input::placeholder,
textarea::placeholder {
  color: var(--text-3);
}

input:focus,
textarea:focus,
select:focus {
  outline: none;
  border-color: rgba(245, 197, 24, 0.95);
  box-shadow: 0 0 0 4px rgba(245, 197, 24, 0.15);
  background: var(--dark-500);
}

input[type="datetime-local"]::-webkit-calendar-picker-indicator {
  filter: invert(1);
  opacity: 0.72;
  cursor: pointer;
}

.actions {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-top: 10px;
  flex-wrap: wrap;
}

.btn-primary,
.btn-secondary {
  min-height: 44px;
  padding: 11px 18px;
  border-radius: 12px;
  font-weight: 700;
  border: 1px solid transparent;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}

.btn-primary {
  background: linear-gradient(135deg, var(--yellow, #f5c518), #ffd74d);
  color: var(--dark-900);
  box-shadow: 0 12px 24px rgba(245, 197, 24, 0.22);
}

.btn-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 16px 28px rgba(245, 197, 24, 0.28);
}

.btn-secondary {
  background: var(--dark-600);
  color: var(--text-2);
  border-color: rgba(255, 255, 255, 0.07);
}

.btn-secondary:hover {
  transform: translateY(-1px);
  background: var(--dark-500);
  border-color: rgba(245, 197, 24, 0.18);
  color: var(--text-1);
}

.back-link {
  display: inline-block;
  margin-top: 18px;
  color: var(--text-2);
  text-decoration: none;
  font-size: 14px;
}

.back-link:hover {
  color: var(--yellow);
}

@media (max-width: 900px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .edit-card {
    padding: 24px;
  }
}

@media (max-width: 768px) {
  .admin-main-content {
    padding: 20px 14px;
  }

  .edit-card {
    padding: 20px;
    border-radius: 16px;
  }

  .edit-header {
    font-size: 26px;
  }

  .actions {
    flex-direction: column;
    align-items: stretch;
  }

  .btn-primary,
  .btn-secondary {
    width: 100%;
  }
}
</style>

<div class="admin-main-content">
  <div class="edit-card">
    <div class="edit-header">Edit Article</div>
    <form method="post" action="" class="edit-form">
      <div class="form-row">
        <div class="form-group">
          <label for="title">Title</label>
          <input type="text" name="title" id="title" value="<?= htmlspecialchars($article['title'] ?? '') ?>" required>
        </div>

        <div class="form-group">
          <label for="category">Category</label>
          <select name="category" id="category">
            <option value="">Select category</option>
            <?php foreach ($categoryOptions as $categoryOption): ?>
              <option value="<?= htmlspecialchars($categoryOption) ?>" <?= (strcasecmp(trim($selectedCategory), trim($categoryOption)) === 0) ? 'selected' : '' ?>>
                <?= htmlspecialchars($categoryOption) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <div class="form-group">
        <label for="summary">Summary</label>
        <textarea name="summary" id="summary"><?= htmlspecialchars($article['summary'] ?? '') ?></textarea>
      </div>

      <div class="form-row">
        <div class="form-group">
          <label for="image_url">Image URL</label>
          <input type="text" name="image_url" id="image_url" value="<?= htmlspecialchars($article['image_url'] ?? '') ?>">
        </div>

        <div class="form-group">
          <label for="article_url">Article URL</label>
          <input type="text" name="article_url" id="article_url" value="<?= htmlspecialchars($article['article_url'] ?? '') ?>">
        </div>
      </div>

      <div class="form-row">
        <div class="form-group">
          <label for="published_at">Published At</label>
          <input type="datetime-local" name="published_at" id="published_at" value="<?= htmlspecialchars($published_at_val) ?>">
        </div>
      </div>

      <div class="actions">
        <button type="submit" class="btn-primary">Update Article</button>
        <a href="articles_list.php" class="btn-secondary">Cancel</a>
      </div>
      <a href="articles_list.php" class="back-link">&larr; Back to Articles List</a>
    </form>
  </div>
</div>

<?php include "includes/footer.php"; ?>

