<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Models\BlogCategory;
use Illuminate\Http\Request;
use App\Services\ImageService;

class BlogManagementController extends Controller
{
    public function index()
    {
        global $conn;
        $stmt = $conn->query("SELECT b.*, bc.name as category_name FROM blogs b LEFT JOIN blog_categories bc ON b.blog_category_id = bc.id ORDER BY b.created_at DESC");
        $blogs = array_map(fn($item) => (object)$item, $stmt->fetchAll());
        return view('admin.blogs.index', compact('blogs'));
    }

    public function create()
    {
        global $conn;
        $categories = array_map(fn($item) => (object)$item, $conn->query("SELECT * FROM blog_categories")->fetchAll());
        return view('admin.blogs.create', compact('categories'));
    }

    public function store(Request $request)
    {
        global $conn;
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|unique:blogs,slug',
            'content' => 'required|string',
            'image' => 'nullable|image|max:2048',
            'image_alt' => 'nullable|string',
            'status' => 'required|in:draft,published',
            'blog_category_id' => 'nullable|integer',
            'published_at' => 'nullable|date',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
        ]);

        $featured_image = null;
        if ($request->hasFile('image')) {
            $path = ImageService::uploadAndOptimize($request->file('image'), 'blogs');
            $featured_image = asset('storage/' . $path);
        }

        $published_at = $validated['published_at'] ?? ($validated['status'] === 'published' ? date('Y-m-d H:i:s') : null);

        $sql = "INSERT INTO blogs (title, slug, content, featured_image, image_alt, status, blog_category_id, published_at, meta_title, meta_description, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute([
            $validated['title'], $validated['slug'], $validated['content'], 
            $featured_image, $validated['image_alt'] ?? '', $validated['status'], 
            $validated['blog_category_id'], $published_at, 
            $validated['meta_title'] ?? '', $validated['meta_description'] ?? ''
        ]);

        return redirect()->route('admin.blogs.index')->with('success', 'Blog post created successfully.');
    }

    public function edit($id)
    {
        global $conn;
        $stmt = $conn->prepare("SELECT * FROM blogs WHERE id = ?");
        $stmt->execute([$id]);
        $blog = (object)$stmt->fetch();
        if (!$blog || !isset($blog->id)) abort(404);

        $categories = array_map(fn($item) => (object)$item, $conn->query("SELECT * FROM blog_categories")->fetchAll());
        return view('admin.blogs.edit', compact('blog', 'categories'));
    }

    public function update(Request $request, $id)
    {
        global $conn;
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string',
            'content' => 'required|string',
            'image' => 'nullable|image|max:2048',
            'image_alt' => 'nullable|string',
            'status' => 'required|in:draft,published',
            'blog_category_id' => 'nullable|integer',
            'published_at' => 'nullable|date',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string',
        ]);

        $sql = "UPDATE blogs SET title=?, slug=?, content=?, image_alt=?, status=?, blog_category_id=?, published_at=?, meta_title=?, meta_description=?, updated_at=NOW()";
        $params = [
            $validated['title'], $validated['slug'], $validated['content'], 
            $validated['image_alt'] ?? '', $validated['status'], 
            $validated['blog_category_id'], $validated['published_at'], 
            $validated['meta_title'] ?? '', $validated['meta_description'] ?? ''
        ];

        if ($request->hasFile('image')) {
            $path = ImageService::uploadAndOptimize($request->file('image'), 'blogs');
            $sql .= ", featured_image=?";
            $params[] = asset('storage/' . $path);
        }

        $sql .= " WHERE id=?";
        $params[] = $id;

        $stmt = $conn->prepare($sql);
        $stmt->execute($params);

        return redirect()->route('admin.blogs.index')->with('success', 'Blog post updated successfully.');
    }

    public function destroy($id)
    {
        global $conn;
        $stmt = $conn->prepare("DELETE FROM blogs WHERE id = ?");
        $stmt->execute([$id]);
        return redirect()->route('admin.blogs.index')->with('success', 'Blog post deleted successfully.');
    }
}
