<?php
/**
 * Blog Detail API Endpoint
 * Fetches single blog data and handles updates
 */

require_once '../../includes/db_connection.php';
require_once '../includes/auth.php';

// Require authentication
requireAuth();

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

$db = Database::getInstance()->getConnection();

// Handle GET request (Fetch blog)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if ($id <= 0) {
            throw new Exception('Invalid blog ID');
        }
        
        $stmt = $db->prepare("
            SELECT b.*, u.username as author_name 
            FROM blogs b 
            LEFT JOIN admin_users u ON b.author_id = u.id 
            WHERE b.id = ?
        ");
        $stmt->execute([$id]);
        $blog = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$blog) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Blog not found']);
            exit;
        }
        
        echo json_encode(['success' => true, 'data' => $blog]);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to fetch blog']);
    }
    exit;
}

// Handle POST request (Create or Update blog)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $isUpdate = $id > 0;
        
        // Get form data
        $title = trim($_POST['title']);
        $content = trim($_POST['content']);
        $category = trim($_POST['category'] ?? 'Uncategorized');
        $visibility = $_POST['visibility'] ?? 'visible';
        $seoTitle = trim($_POST['seo_title']);
        $seoDescription = trim($_POST['seo_description']);
        $excerpt = trim($_POST['excerpt'] ?? '');
        
        // Validation
        if (empty($title)) {
            throw new Exception('Title is required');
        }
        
        // Generate slug
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
        
        // Handle Image Upload
        $featuredImage = null;
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../../assets/images/blogs/';
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['featured_image']['name']);
            $targetPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $targetPath)) {
                $featuredImage = 'assets/images/blogs/' . $fileName;
            }
        }
        
        if ($isUpdate) {
            // Update existing blog
            $query = "UPDATE blogs SET 
                title = ?, 
                content = ?, 
                category = ?, 
                visibility = ?, 
                seo_title = ?, 
                seo_description = ?,
                excerpt = ?,
                updated_at = NOW()
            ";
            
            $params = [$title, $content, $category, $visibility, $seoTitle, $seoDescription, $excerpt];
            
            if ($featuredImage) {
                $query .= ", featured_image = ?";
                $params[] = $featuredImage;
            }
            
            $query .= " WHERE id = ?";
            $params[] = $id;
            
            $stmt = $db->prepare($query);
            $stmt->execute($params);
            
            echo json_encode(['success' => true, 'message' => 'Blog updated successfully']);
            
        } else {
            // Create new blog
            // Check for duplicate slug
            $stmt = $db->prepare("SELECT id FROM blogs WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetch()) {
                $slug .= '-' . time();
            }
            
            $query = "INSERT INTO blogs (
                title, slug, content, category, visibility, 
                seo_title, seo_description, excerpt, featured_image, 
                author_id, published_at, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            // Get current user ID (assuming it's stored in session from auth.php)
            $authorId = $_SESSION['admin_user_id'] ?? 1; // Fallback to 1 if not set
            
            $params = [
                $title, $slug, $content, $category, $visibility,
                $seoTitle, $seoDescription, $excerpt, 
                $featuredImage ?: 'assets/images/extra/card/img-1.jpg', // Default image
                $authorId
            ];
            
            $stmt = $db->prepare($query);
            $stmt->execute($params);
            
            echo json_encode(['success' => true, 'message' => 'Blog created successfully', 'id' => $db->lastInsertId()]);
        }
        
    } catch (Exception $e) {
        error_log('Blog save error: ' . $e->getMessage());
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to save blog: ' . $e->getMessage()]);
    }
    exit;
}

http_response_code(405);
echo json_encode(['success' => false, 'message' => 'Method not allowed']);
?>
