<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) { session_start(); }

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

header('Content-Type: application/json; charset=utf-8');

// ── Auth guard ────────────────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
    exit();
}
try {
    $u = $pdo->prepare("SELECT is_admin FROM users WHERE id = :id");
    $u->execute(['id' => $_SESSION['user_id']]);
    $row = $u->fetch(PDO::FETCH_ASSOC);
    if (!$row || $row['is_admin'] != 1) {
        echo json_encode(['status' => '0', 'msg' => 'Unauthorized']);
        exit();
    }
} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Auth error']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$action = trim($_POST['action'] ?? '');

// ════════════════════════════════════════════════════════════════
// Helper: upload thumbnail
// Returns the web-root-relative path, or empty string on failure
// ════════════════════════════════════════════════════════════════
function uploadThumbnail(array $file, string $old_path = ''): string
{
    $upload_dir  = dirname(__DIR__, 2) . '/assets/images/blog/';
    $upload_url  = '/assets/images/blog/';

    // Create directory if needed
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $allowed_types = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    $allowed_exts  = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $max_size      = 2 * 1024 * 1024; // 2 MB

    if ($file['error'] !== UPLOAD_ERR_OK) {
        return $old_path; // keep existing if no new file
    }

    if ($file['size'] > $max_size) {
        http_response_code(400);
        echo json_encode(['status' => '0', 'msg' => 'Thumbnail must be under 2 MB.']);
        exit();
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime, $allowed_types)) {
        http_response_code(400);
        echo json_encode(['status' => '0', 'msg' => 'Invalid image type. Only JPG, PNG, WEBP, GIF allowed.']);
        exit();
    }

    $ext      = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed_exts)) {
        $ext = 'jpg'; // fallback
    }

    $filename = 'blog_' . time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
    $dest     = $upload_dir . $filename;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        http_response_code(500);
        echo json_encode(['status' => '0', 'msg' => 'Failed to save uploaded image.']);
        exit();
    }

    // Delete old file if it was an uploaded one
    if (!empty($old_path) && strpos($old_path, '/assets/images/blog/') === 0) {
        $old_full = dirname(__DIR__, 2) . $old_path;
        if (file_exists($old_full)) {
            @unlink($old_full);
        }
    }

    return $upload_url . $filename;
}

// ════════════════════════════════════════════════════════════════
// Helper: generate unique slug
// ════════════════════════════════════════════════════════════════
function generateSlug(PDO $pdo, string $title, int $exclude_id = 0): string
{
    $base = strtolower(trim($title));
    $base = preg_replace('/[^a-z0-9\s-]/', '', $base);
    $base = preg_replace('/[\s-]+/', '-', $base);
    $base = trim($base, '-');
    if (empty($base)) $base = 'post';

    $slug  = $base;
    $count = 0;
    while (true) {
        $s = $pdo->prepare("SELECT COUNT(*) FROM blog_posts WHERE slug = :slug AND id != :eid");
        $s->execute(['slug' => $slug, 'eid' => $exclude_id]);
        if ((int)$s->fetchColumn() === 0) break;
        $count++;
        $slug = $base . '-' . $count;
    }
    return $slug;
}

// ════════════════════════════════════════════════════════════════
// ACTION: get_post — load a single post for editing
// ════════════════════════════════════════════════════════════════
if ($action === 'get_post') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid post ID']); exit(); }

    try {
        $s = $pdo->prepare("SELECT * FROM blog_posts WHERE id = :id LIMIT 1");
        $s->execute(['id' => $id]);
        $post = $s->fetch(PDO::FETCH_ASSOC);

        if (!$post) {
            echo json_encode(['status' => '0', 'msg' => 'Post not found']);
        } else {
            echo json_encode(['status' => '1', 'post' => $post]);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: create_post
// ════════════════════════════════════════════════════════════════
if ($action === 'create_post') {
    $title     = trim($_POST['title']     ?? '');
    $content   = trim($_POST['content']   ?? '');
    $excerpt   = trim($_POST['excerpt']   ?? '');
    $category  = trim($_POST['category']  ?? 'General');
    $author    = trim($_POST['author']    ?? 'Admin');
    $read_time = trim($_POST['read_time'] ?? '5 min read');
    $status    = in_array($_POST['status'] ?? '', ['published', 'draft']) ? $_POST['status'] : 'draft';
    $slug_raw  = trim($_POST['slug']      ?? '');

    if (empty($title) || empty($content) || empty($excerpt)) {
        echo json_encode(['status' => '0', 'msg' => 'Title, content, and excerpt are required.']);
        exit();
    }

    // Resolve slug
    $slug = !empty($slug_raw)
        ? generateSlug($pdo, $slug_raw)
        : generateSlug($pdo, $title);

    // Handle thumbnail upload
    $thumbnail = '';
    if (!empty($_FILES['thumbnail_file']['name'])) {
        $thumbnail = uploadThumbnail($_FILES['thumbnail_file']);
    }

    try {
        $pdo->prepare(
            "INSERT INTO blog_posts (title, slug, category, author, excerpt, content, thumbnail, read_time, status, created_at)
             VALUES (:title, :slug, :category, :author, :excerpt, :content, :thumbnail, :read_time, :status, NOW())"
        )->execute([
            'title'     => $title,
            'slug'      => $slug,
            'category'  => $category,
            'author'    => $author,
            'excerpt'   => $excerpt,
            'content'   => $content,
            'thumbnail' => $thumbnail,
            'read_time' => $read_time,
            'status'    => $status,
        ]);

        echo json_encode(['status' => '1', 'msg' => 'Blog post created successfully!']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: update_post
// ════════════════════════════════════════════════════════════════
if ($action === 'update_post') {
    $id        = (int)($_POST['id']       ?? 0);
    $title     = trim($_POST['title']     ?? '');
    $content   = trim($_POST['content']   ?? '');
    $excerpt   = trim($_POST['excerpt']   ?? '');
    $category  = trim($_POST['category']  ?? 'General');
    $author    = trim($_POST['author']    ?? 'Admin');
    $read_time = trim($_POST['read_time'] ?? '5 min read');
    $status    = in_array($_POST['status'] ?? '', ['published', 'draft']) ? $_POST['status'] : 'draft';
    $slug_raw  = trim($_POST['slug']      ?? '');
    $thumb_existing = trim($_POST['thumbnail_existing'] ?? '');

    if (!$id)                  { echo json_encode(['status' => '0', 'msg' => 'Invalid post ID.']); exit(); }
    if (empty($title))         { echo json_encode(['status' => '0', 'msg' => 'Title is required.']); exit(); }
    if (empty($content))       { echo json_encode(['status' => '0', 'msg' => 'Content is required.']); exit(); }
    if (empty($excerpt))       { echo json_encode(['status' => '0', 'msg' => 'Excerpt is required.']); exit(); }

    // Fetch current post to get existing thumbnail
    $current = $pdo->prepare("SELECT thumbnail FROM blog_posts WHERE id = :id");
    $current->execute(['id' => $id]);
    $current_row = $current->fetch(PDO::FETCH_ASSOC);
    if (!$current_row) { echo json_encode(['status' => '0', 'msg' => 'Post not found.']); exit(); }

    $old_thumb = $current_row['thumbnail'];

    // Resolve slug
    $slug = !empty($slug_raw)
        ? generateSlug($pdo, $slug_raw, $id)
        : generateSlug($pdo, $title,    $id);

    // Thumbnail: new upload > cleared (empty existing) > keep old
    $thumbnail = $old_thumb; // default: keep
    if (!empty($_FILES['thumbnail_file']['name'])) {
        $thumbnail = uploadThumbnail($_FILES['thumbnail_file'], $old_thumb);
    } elseif ($thumb_existing === '') {
        // User explicitly cleared thumbnail
        if (!empty($old_thumb) && strpos($old_thumb, '/assets/images/blog/') === 0) {
            $old_full = dirname(__DIR__, 2) . $old_thumb;
            if (file_exists($old_full)) @unlink($old_full);
        }
        $thumbnail = '';
    }

    try {
        $pdo->prepare(
            "UPDATE blog_posts
             SET title=:title, slug=:slug, category=:category, author=:author,
                 excerpt=:excerpt, content=:content, thumbnail=:thumbnail,
                 read_time=:read_time, status=:status, updated_at=NOW()
             WHERE id=:id"
        )->execute([
            'title'     => $title,
            'slug'      => $slug,
            'category'  => $category,
            'author'    => $author,
            'excerpt'   => $excerpt,
            'content'   => $content,
            'thumbnail' => $thumbnail,
            'read_time' => $read_time,
            'status'    => $status,
            'id'        => $id,
        ]);

        echo json_encode(['status' => '1', 'msg' => 'Blog post updated successfully!']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

// ════════════════════════════════════════════════════════════════
// ACTION: delete_post
// ════════════════════════════════════════════════════════════════
if ($action === 'delete_post') {
    $id = (int)($_POST['id'] ?? 0);
    if (!$id) { echo json_encode(['status' => '0', 'msg' => 'Invalid post ID.']); exit(); }

    try {
        // Fetch thumbnail path before deleting
        $s = $pdo->prepare("SELECT thumbnail FROM blog_posts WHERE id = :id");
        $s->execute(['id' => $id]);
        $row = $s->fetch(PDO::FETCH_ASSOC);

        if ($row && !empty($row['thumbnail']) && strpos($row['thumbnail'], '/assets/images/blog/') === 0) {
            $path = dirname(__DIR__, 2) . $row['thumbnail'];
            if (file_exists($path)) @unlink($path);
        }

        $pdo->prepare("DELETE FROM blog_posts WHERE id = :id")->execute(['id' => $id]);

        echo json_encode(['status' => '1', 'msg' => 'Post deleted successfully.']);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'DB error: ' . $e->getMessage()]);
    }
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Unknown action.']);