<?php

namespace App\Http\Controllers;

use App\Enums\PostStatus;
use App\Enums\PostType;
use App\Models\Platform;
use App\Models\SocialAccount;
use App\Models\SocialPost;
use Inertia\Inertia;

class CalendarController extends Controller
{
    protected $user, $workspace;

    public function __construct()
    {
        $this->user = auth_user();
        $this->workspace = current_workspace();
    }


    public function index()
    {


        $posts = SocialPost::with(['account', 'platform', 'files'])
            ->where('user_id', $this->user->id)
            ->search(['account:name' , 'content'])
            ->filterByTab()
            ->latest()
            ->when(request()->input('account_ids'), function ($query) {
                $query->whereIn('account_id', request()->input('account_ids'));
            })
            ->get()
            ->map(fn($post) => [
                'id' => $post->id,
                'author' => $post->account?->name ?? 'Unknown',
                'avatar' => $post->account?->avatar ?? null,
                'content' => $post->content,
                'postType' => PostType::tryFrom($post->post_type)?->name ?? 'FEED',
                'status' => PostStatus::tryFrom($post->status)?->name ?? 'PENDING',
                'dateGroup' => optional($post->schedule_time ?? $post->posted_at ?? $post->created_at)->format('Y-m-d\TH:i:s\Z'),
                'date' => $post->schedule_time ?? $post->posted_at ?? $post->created_at,
                'platform' => $post->platform,
                'platform_slug' => $post->platform?->slug,
                'account' => [
                    'name' => $post->account?->name,
                    'avatar' => $post->account?->avatar ?? null,
                ],
                'media' => $post->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(),
                'engagement' => [
                    'reactions' => ['like' => 0, 'heart' => 0, 'laugh' => 0],
                    'comments' => 0,
                    'shares' => 0,
                ],
            ])->toArray();


        return Inertia::render("Calender/Index", [
            "platforms" => Platform::all(),
            "accounts" => SocialAccount::with('platform')
                ->where('user_id', $this->user->id)
                ->where('workspace_id', $this->workspace->id)
                ->get(),

            "posts" => $posts
        ]);
    }
}
