<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/csrf.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ./');
    exit;
}

if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    setFlash('error', 'Invalid CSRF Token.');
    header('Location: ./');
    exit;
}

$db = getDB();
$action = $_POST['action'] ?? '';
$id = $_POST['id'] ?? null;

$judul = $_POST['judul'];
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $judul))); // Create slug
$isi_konten = $_POST['isi_konten'];
$ringkasan = $_POST['ringkasan'];
$kategori_id = $_POST['kategori_id'];
$is_published = $_POST['is_published'];
$created_by = $_SESSION['user_id'];

// Handle upload gambar
$gambar = null;
if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] === UPLOAD_ERR_OK) {
    $tmp_name = $_FILES['gambar']['tmp_name'];
    $name = basename($_FILES['gambar']['name']);
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    
    if (in_array($ext, ['jpg', 'jpeg', 'png', 'webp'])) {
        $gambar = uniqid() . '.' . $ext;
        move_uploaded_file($tmp_name, '../../assets/uploads/edukasi/' . $gambar);
    }
}

try {
    if ($action === 'tambah') {
        $sql = "INSERT INTO edukasi (kategori_id, judul, slug, ringkasan, isi_konten, gambar, is_published, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$kategori_id, $judul, $slug, $ringkasan, $isi_konten, $gambar, $is_published, $created_by]);
        setFlash('success', 'Artikel berhasil ditambahkan.');
    } elseif ($action === 'edit' && $id) {
        if ($gambar) {
            $sql = "UPDATE edukasi SET kategori_id=?, judul=?, slug=?, ringkasan=?, isi_konten=?, gambar=?, is_published=? WHERE id=?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$kategori_id, $judul, $slug, $ringkasan, $isi_konten, $gambar, $is_published, $id]);
        } else {
            $sql = "UPDATE edukasi SET kategori_id=?, judul=?, slug=?, ringkasan=?, isi_konten=?, is_published=? WHERE id=?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$kategori_id, $judul, $slug, $ringkasan, $isi_konten, $is_published, $id]);
        }
        setFlash('success', 'Artikel berhasil diperbarui.');
    }
} catch (PDOException $e) {
    setFlash('error', 'Terjadi kesalahan sistem: ' . $e->getMessage());
}

header('Location: ./');
exit;
