<?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;
}

$selectedCategory = $_POST['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'];
}

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("INSERT INTO articles (title, summary, category, image_url, article_url, published_at) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $summary, $category, $image_url, $article_url, $published_at]);
    } catch (Throwable $e) {
        die('Article save failed: ' . htmlspecialchars($e->getMessage()));
    }

    header('Location: articles_list.php');
    exit;
}

// Include Premium Admin Header & Sidebar
include "includes/header.php";
include "includes/sidebar.php";
?>

<style>
  /* ── Layout & Page Header ── */
  .dash { max-width: 900px; margin: 0 auto; padding: 30px 26px; z-index: 1; position: relative; }
  
  .page-header { display: flex; align-items: flex-end; justify-content: space-between; margin-bottom: 28px; flex-wrap: wrap; gap: 14px; }
  .ph-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 0.6rem; letter-spacing: 3.5px; text-transform: uppercase; color: var(--yellow-dim); margin-bottom: 6px; display: flex; align-items: center; gap: 7px; }
  .ph-eyebrow::before { content: ''; display: inline-block; width: 20px; height: 2px; background: var(--yellow); border-radius: 2px; }
  .ph-title { font-family: 'Syne', sans-serif; font-size: 2rem; font-weight: 800; color: var(--text-1); letter-spacing: -0.5px; line-height: 1.1; }

  /* ── Form Panel ── */
  .form-panel { background: var(--dark-700); border: 1px solid rgba(255,255,255,0.05); border-radius: 14px; padding: 30px; }
  
  .section-title { font-family: 'Syne', sans-serif; font-size: 1.1rem; font-weight: 700; color: var(--text-1); border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 10px; margin-bottom: 20px; margin-top: 20px; }
  .section-title:first-child { margin-top: 0; }
  .section-title i { color: var(--yellow); margin-right: 8px; font-size: 1rem; }

  .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

  .form-group { margin-bottom: 18px; }
  .form-label { display: block; font-family: 'JetBrains Mono', monospace; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; color: var(--text-2); margin-bottom: 8px; font-weight: 600; }
  
  .form-control { width: 100%; padding: 12px 16px; background: var(--dark-800); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; color: var(--text-1); font-size: 0.9rem; transition: 0.3s; font-family: 'Manrope', sans-serif; }
  .form-control:focus { outline: none; border-color: var(--yellow); box-shadow: 0 0 0 3px var(--yellow-glass); }
  .form-control::placeholder { color: rgba(255,255,255,0.2); }
  
  /* Make datetime picker icon visible on dark background */
  input[type="datetime-local"]::-webkit-calendar-picker-indicator { filter: invert(1); opacity: 0.6; cursor: pointer; }

  textarea.form-control { min-height: 120px; resize: vertical; }

  /* ── Action Buttons ── */
  .form-actions { display: flex; gap: 15px; margin-top: 30px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.05); }
  .btn-submit { background: var(--yellow); color: var(--dark-900); padding: 12px 28px; border: none; border-radius: 8px; font-weight: 700; font-size: 0.95rem; cursor: pointer; transition: 0.2s; display: flex; align-items: center; gap: 8px; }
  .btn-submit:hover { background: var(--yellow-bright); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(245,197,24,0.3); }
  
  .btn-cancel { background: rgba(255,255,255,0.05); color: var(--text-1); padding: 12px 28px; border: 1px solid rgba(255,255,255,0.1); border-radius: 8px; font-weight: 600; font-size: 0.95rem; cursor: pointer; text-decoration: none; transition: 0.2s; display: flex; align-items: center; gap: 8px; }
  .btn-cancel:hover { background: rgba(255,255,255,0.1); color: #fff; }

  @media (max-width: 768px) {
      .grid-2 { grid-template-columns: 1fr; gap: 10px; }
      .form-actions { flex-direction: column; }
      .btn-submit, .btn-cancel { width: 100%; justify-content: center; }
  }
</style>

<main class="dash">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <div class="ph-eyebrow">Content Management</div>
            <div class="ph-title">Create <strong>Article</strong></div>
        </div>
    </div>

    <!-- Form Panel -->
    <div class="form-panel">
        <form method="post" action="">
            
            <h3 class="section-title"><i class="fas fa-pen-nib"></i> Article Details</h3>
            
            <div class="form-group">
                <label class="form-label" for="title">Title</label>
                <input type="text" name="title" id="title" class="form-control" placeholder="Enter article title..." required>
            </div>

            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="category">Category</label>
                    <select name="category" id="category" class="form-control" required>
                        <option value="">Select category</option>
                        <?php foreach ($categoryOptions as $categoryOption): ?>
                            <option value="<?= htmlspecialchars($categoryOption) ?>" <?= ($selectedCategory !== '' && strcasecmp(trim($selectedCategory), trim($categoryOption)) === 0) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($categoryOption) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label" for="published_at">Publish Date & Time</label>
                    <input type="datetime-local" name="published_at" id="published_at" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label" for="summary">Summary</label>
                <textarea name="summary" id="summary" class="form-control" placeholder="Write a short summary or excerpt for the article..."></textarea>
            </div>

            <h3 class="section-title"><i class="fas fa-link"></i> Media & Links</h3>

            <div class="grid-2">
                <div class="form-group">
                    <label class="form-label" for="image_url">Cover Image URL</label>
                    <input type="text" name="image_url" id="image_url" class="form-control" placeholder="https://example.com/image.jpg">
                </div>
                <div class="form-group">
                    <label class="form-label" for="article_url">External Article URL</label>
                    <input type="text" name="article_url" id="article_url" class="form-control" placeholder="https://example.com/full-article">
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="form-actions">
                <button type="submit" class="btn-submit">
                    <i class="fas fa-paper-plane"></i> Publish Article
                </button>
                <a href="articles_list.php" class="btn-cancel">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</main>

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