<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\Category;
use App\Models\ContentFile;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class ContentController extends Controller
{
    public function index(Request $request)
    {
        $query = Content::with('category')->latest();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
        }

        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        $contents = $query->paginate(20);
        $categories = Category::where('status', 'active')->get();

        return view('admin.contents.index', compact('contents', 'categories'));
    }

    public function create()
    {
        $categories = Category::where('status', 'active')->get();
        return view('admin.contents.create', compact('categories'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'nullable|exists:categories,id',
            'content_type' => 'required|in:video,audio,image,text,pdf,mixed',
            'description' => 'nullable|string',
            'is_premium' => 'boolean',
            'price' => 'nullable|numeric',
            'status' => 'required|in:draft,published,archived',
            'file' => 'nullable|file|max:51200', // 50MB max for now
        ]);

        $validated['slug'] = Str::slug($validated['title']) . '-' . time();
        $validated['published_at'] = $validated['status'] == 'published' ? now() : null;

        $content = Content::create($validated);

        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $path = $file->store('contents/' . $content->id, 'public');

            ContentFile::create([
                'content_id' => $content->id,
                'file_type' => $this->mapMimeTypeToEnum($file->getMimeType()),
                'file_url' => Storage::url($path),
                'file_name' => $file->getClientOriginalName(),
                'file_size' => $file->getSize(),
                'mime_type' => $file->getMimeType(),
                'is_downloadable' => true,
            ]);
        }

        return redirect()->route('admin.contents.index')->with('success', 'محتوا با موفقیت ایجاد شد.');
    }

    public function edit(Content $content)
    {
        $categories = Category::where('status', 'active')->get();
        return view('admin.contents.edit', compact('content', 'categories'));
    }

    public function update(Request $request, Content $content)
    {
         $validated = $request->validate([
            'title' => 'required|string|max:255',
            'category_id' => 'nullable|exists:categories,id',
            'content_type' => 'required|in:video,audio,image,text,pdf,mixed',
            'description' => 'nullable|string',
            'is_premium' => 'boolean',
            'price' => 'nullable|numeric',
            'status' => 'required|in:draft,published,archived',
            'file' => 'nullable|file|max:51200',
        ]);

        $content->update($validated);

        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $path = $file->store('contents/' . $content->id, 'public');

            ContentFile::create([
                'content_id' => $content->id,
                'file_type' => $this->mapMimeTypeToEnum($file->getMimeType()),
                'file_url' => Storage::url($path),
                'file_name' => $file->getClientOriginalName(),
                'file_size' => $file->getSize(),
                'mime_type' => $file->getMimeType(),
                'is_downloadable' => true,
            ]);
        }

        return redirect()->route('admin.contents.index')->with('success', 'محتوا با موفقیت ویرایش شد.');
    }

    public function destroy(Content $content)
    {
        $content->delete();
        return redirect()->route('admin.contents.index')->with('success', 'محتوا با موفقیت حذف شد.');
    }

    private function mapMimeTypeToEnum($mime) {
        if (str_contains($mime, 'video')) return 'video';
        if (str_contains($mime, 'audio')) return 'audio';
        if (str_contains($mime, 'image')) return 'image';
        if (str_contains($mime, 'pdf')) return 'pdf';
        return 'document';
    }
}
