<?php

namespace App\Http\Controllers;

use App\Enums\FileKey;
use App\Enums\PostType;
use App\Http\Requests\PostTemplateRequest;
use App\Http\Requests\PostTemplateUpdateRequest;
use App\Models\AiTemplate;
use App\Models\Platform;
use App\Models\PostTemplate;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use App\Traits\PostManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class SocialTemplateController extends Controller
{
    use Fileable, ModelAction, PostManager;
    protected $user;



    public function __construct()
    {

        $this->user = auth_user('web');

    }


    public function index()
    {
        $filters = request()->only(['search', 'platform_id']);

        // Post Templates
        $postTemplates = PostTemplate::where('user_id', auth()->id())
            ->with(['platform', 'files'])
            ->when($filters['search'] ?? null, fn($q, $search) => $q->where('title', 'like', "%{$search}%"))
            ->when($filters['platform_id'] ?? null, fn($q, $platformId) => $q->where('platform_id', $platformId))
            ->latest()
            ->paginate(paginateNumber())
            ->through(fn($template) => [
                'id' => $template->id,
                'title' => $template->title,
                'description' => $template->description,
                'content' => $template->content,
                'platform' => $template->platform,
                'images' => $template->files->map(fn($file) => [
                    'id' => $file->id,
                    'url' => imageURL($file, 'gallery'),
                    'thumbnail' => imageURL($file, 'gallery'),
                    'alt' => $file->pivot->alt ?? $file->name,
                    'isVideo' => getFileTypeFromExtension($file->extension) === 'video',
                ])->toArray(),
            ]);

        // AI Templates
        $aiTemplates = AiTemplate::where('user_id', auth()->id())
            ->with('platform')
            ->when($filters['search'] ?? null, fn($q, $search) => $q->where('name', 'like', "%{$search}%"))
            ->when($filters['platform_id'] ?? null, fn($q, $platformId) => $q->where('platform_id', $platformId))
            ->latest()
            ->paginate(paginateNumber());



        return Inertia::render("Template/Index", [
            'post_templates' => $postTemplates,
            'ai_templates' => $aiTemplates,
            'platforms' => Platform::select('id', 'name', 'slug')->get(),
            'search' => $filters['search'] ?? null,
            'platform_id' => $filters['platform_id'] ?? null,
        ]);
    }


    public function store(PostTemplateRequest $request)
    {
        $data = $request->validated();


        DB::beginTransaction();
        try {
            $template = PostTemplate::create([
                'user_id' => $this->user->id,
                'title' => $data['name'] ?? null,
                'description' => $data['description'] ?? null,
                'content' => $data['content'],
                'link' => $data['link'] ?? null,
                'platform_id' => $data['platform_id'] ?? null,
            ]);

            foreach ($data['files'] ?? [] as $file) {

                if (!empty($file['id'])) {
                    $galleryFile = $this->user->files()->find($file['id']);
                    if ($galleryFile) {
                        $template->files()->attach($galleryFile->id, [
                            'caption' => $file['caption'] ?? null,
                            'alt' => $file['alt'] ?? null,
                            'order' => $file['order'] ?? null
                        ]);
                    }
                } elseif (!empty($file['upload'])) {
                    $storedFile = $this->storeFile(
                        file: $file['upload'],
                        location: config('settings.file_path.gallery.path')
                    );

                    $savedFile = $this->saveFile(
                        $template,
                        $storedFile,
                        FileKey::TEMPLATE_FILE->value
                    );

                    $template->files()->attach($savedFile->id, [
                        'caption' => $file['caption'] ?? null,
                        'alt' => $file['alt'] ?? null,
                        'order' => $file['order'] ?? null
                    ]);
                }
            }

            DB::commit();
            return back()->with('success', 'Social template created successfully!');
        } catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            report($e);
            return back()->with('error', 'Failed to create social template.');
        }
    }

    public function edit($id)
    {
        $media = $this->getMedia($this->user);
        $templates = $this->getTemplates($this->user);
        $aiTemplates = $this->getAiTemplates($this->user);


        $template = PostTemplate::with(['platform', 'files'])->findOrFail($id);

        $postData = $this->formatPostData($template, true);

        return Inertia::render('Template/Edit', [
            'post' => $postData,
            'media' => $media,
            'post_templates' => $templates,
            'ai_templates' => $aiTemplates,
            "platforms" => Platform::all(),
        ]);
    }




    private function formatPostData($item, $isTemplate = false)
    {
        return [
            'id' => $item->id,
            'is_template' => $isTemplate,
            'title' => $isTemplate ? $item->title : null,
            'postTypes' => [
                strtolower($item->platform?->slug ?? 'unknown') => strtolower(
                    $isTemplate
                    ? (PostType::FEED)->name   // default for template
                    : PostType::tryFrom($item->post_type)?->name ?? 'feed'
                ),
            ],
            'content' => $item->content,
            'files' => $item->files->map(fn($file) => [
                'id' => $file->id,
                'url' => imageURL($file, 'gallery'),
                'caption' => $file->pivot->caption,
                'alt' => $file->pivot->alt,
                'order' => $file->pivot->order,
            ])->values() ?? [],
            'links' => $isTemplate ? [$item->link] : ($item->links ?? []),
            'active_platform' => $item->platform?->slug ?? 'facebook',
            'accounts' => $isTemplate ? [] : $item->account,
            'is_scheduled' => $isTemplate ? '0' : ($item->is_scheduled ?? '0'),
            'scheduled_time' => $isTemplate ? null : $item->schedule_time,
            'is_draft' => $isTemplate ? '0' : ($item->is_draft ?? '0'),
        ];
    }

    public function update(PostTemplateUpdateRequest $request)
    {
        $data = $request->validated();

        DB::beginTransaction();
        try {
            $template = PostTemplate::with('files')->findOrFail($request->input('id'));

            $template->update([
                'title' => $data['name'] ?? $template->title,
                'description' => $data['description'] ?? $template->description,
                'content' => $data['content'],
                'link' => $data['link'] ?? $template->link,
                'platform_id' => $data['platform_id'] ?? $template->platform_id,
            ]);

            $template->files()->detach();

            foreach ($data['files'] ?? [] as $file) {
                if (!empty($file['id'])) {
                    $galleryFile = $this->user->files()->find($file['id']);
                    if ($galleryFile) {
                        $template->files()->attach($galleryFile->id, [
                            'caption' => $file['caption'] ?? null,
                            'alt' => $file['alt'] ?? null,
                            'order' => $file['order'] ?? null,
                        ]);
                    }
                } elseif (!empty($file['upload'])) {
                    $storedFile = $this->storeFile(
                        file: $file['upload'],
                        location: config('settings.file_path.gallery.path')
                    );

                    $savedFile = $this->saveFile(
                        $template,
                        $storedFile,
                        FileKey::TEMPLATE_FILE->value
                    );

                    $template->files()->attach($savedFile->id, [
                        'caption' => $file['caption'] ?? null,
                        'alt' => $file['alt'] ?? null,
                        'order' => $file['order'] ?? null,
                    ]);
                }
            }

            DB::commit();
            return back()->with('success', 'Template updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            return back()->with('error', 'Failed to update template.');
        }
    }



    public function delete(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:post_templates,id'
        ]);

        $postTemplate = PostTemplate::findOrFail($request->input('id'));
        $postTemplate->delete();

        return redirect()->back()->with('success', 'Post Template Deleted');

    }




}
