<?php
session_start();
include '../../includes/db.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$input = file_get_contents('php://input');
$data  = json_decode($input, true);

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'Invalid data']);
    exit;
}

$title     = trim($data['title'] ?? 'Untitled');
$raw_blocks= $data['content'] ?? [];
$content   = json_encode($raw_blocks);
$image_url = trim($data['image_url'] ?? '');
$excerpt   = $data['excerpt']   ?? '';
$status    = in_array($data['status'] ?? '', ['published', 'draft']) ? $data['status'] : 'published';
$editId    = isset($data['edit_id']) ? (int)$data['edit_id'] : 0;
$post_type = ($data['post_type'] === 'services') ? 'services' : 'blog';

// 1. If image_url is a base64 Data URL, decode and save to file
if (preg_match('/^data:image\/(\w+);base64,/', $image_url, $type)) {
    $data_b64 = substr($image_url, strpos($image_url, ',') + 1);
    $data_b64 = base64_decode($data_b64);
    if ($data_b64 !== false) {
        $ext = strtolower($type[1]);
        if ($ext === 'jpeg') $ext = 'jpg';
        $uploadDir = realpath(__DIR__ . '/../../uploads') . '/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        $fname = md5(uniqid(rand(), true)) . '.' . $ext;
        $dest = $uploadDir . $fname;
        file_put_contents($dest, $data_b64);
        $image_url = '/bm/uploads/' . $fname;
    }
}

// 2. If image_url is still empty, auto-extract the first image block from the content
if (empty($image_url) && !empty($raw_blocks) && isset($raw_blocks['blocks']) && is_array($raw_blocks['blocks'])) {
    foreach ($raw_blocks['blocks'] as $block) {
        if ($block['type'] === 'image' && !empty($block['data']['file']['url'])) {
            $image_url = $block['data']['file']['url'];
            break;
        } elseif ($block['type'] === 'gallery' && !empty($block['data']['urls'][0])) {
            $image_url = $block['data']['urls'][0];
            break;
        }
    }
}

if ($post_type === 'services') {
    $view_url   = '/bm/service-detail/' . urlencode($title);
    $manage_url = '../manage_services.php';

    if ($editId > 0) {
        $stmt = $conn->prepare("UPDATE services SET title=?, description=?, image_url=?, status=? WHERE id=?");
        if (!$stmt) { echo json_encode(['success' => false, 'message' => $conn->error]); exit; }
        $stmt->bind_param("ssssi", $title, $content, $image_url, $status, $editId);
        if ($stmt->execute()) {
            echo json_encode([
                'success'    => true, 
                'id'         => $editId, 
                'action'     => 'updated',
                'post_type'  => 'services',
                'image_url'  => $image_url,
                'view_url'   => $view_url,
                'manage_url' => $manage_url,
                'message'    => 'Service updated successfully!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => $conn->error]);
        }
    } else {
        $stmt = $conn->prepare("INSERT INTO services (title, description, image_url, status, created_at) VALUES (?, ?, ?, ?, NOW())");
        if (!$stmt) { echo json_encode(['success' => false, 'message' => $conn->error]); exit; }
        $stmt->bind_param("ssss", $title, $content, $image_url, $status);
        if ($stmt->execute()) {
            $newId = $stmt->insert_id;
            echo json_encode([
                'success'    => true, 
                'id'         => $newId, 
                'action'     => 'created',
                'post_type'  => 'services',
                'image_url'  => $image_url,
                'view_url'   => $view_url,
                'manage_url' => $manage_url,
                'message'    => 'Service published successfully!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => $conn->error]);
        }
    }
} else {
    $view_url   = '/bm/blog_post/' . urlencode($title);
    $manage_url = '../manage_blogs.php';

    if ($editId > 0) {
        $stmt = $conn->prepare("UPDATE blogs SET title=?, content=?, image_url=?, status=? WHERE id=?");
        if (!$stmt) { echo json_encode(['success' => false, 'message' => $conn->error]); exit; }
        $stmt->bind_param("ssssi", $title, $content, $image_url, $status, $editId);
        if ($stmt->execute()) {
            echo json_encode([
                'success'    => true, 
                'id'         => $editId, 
                'action'     => 'updated',
                'post_type'  => 'blog',
                'image_url'  => $image_url,
                'view_url'   => $view_url,
                'manage_url' => $manage_url,
                'message'    => 'Blog post updated successfully!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => $conn->error]);
        }
    } else {
        $stmt = $conn->prepare("INSERT INTO blogs (title, content, image_url, status, created_at) VALUES (?, ?, ?, ?, NOW())");
        if (!$stmt) { echo json_encode(['success' => false, 'message' => $conn->error]); exit; }
        $stmt->bind_param("ssss", $title, $content, $image_url, $status);
        if ($stmt->execute()) {
            $newId = $stmt->insert_id;
            echo json_encode([
                'success'    => true, 
                'id'         => $newId, 
                'action'     => 'created',
                'post_type'  => 'blog',
                'image_url'  => $image_url,
                'view_url'   => $view_url,
                'manage_url' => $manage_url,
                'message'    => 'Blog post published successfully!'
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => $conn->error]);
        }
    }
}
$stmt->close();
?>
