<?php

namespace App\Http\Controllers;

use App\Enums\BulkActionEnum;
use App\Enums\FileKey;
use App\Enums\StatusEnum;
use App\Http\Requests\CampaignStoreRequest;
use App\Http\Requests\CampaignUpdateRequest;
use App\Http\Services\AnalyticsService;
use App\Models\AiTemplate;
use App\Models\Campaign;
use App\Models\Platform;
use App\Models\PostTemplate;
use App\Models\SocialAccount;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use App\Traits\PostManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Inertia\Inertia;

class CampaignController extends Controller
{
    protected $user, $workspace, $analyticsService;

    use Fileable, ModelAction, PostManager;

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

    }
    public function index()
    {
        return Inertia::render("Campaign/Index", [
            'campaigns' => Campaign::with('posts.account')
                ->where([
                    'user_id' => $this->user->id,
                    'workspace_id' => $this->workspace->id,
                ])
                ->search(['name'])
                ->filter(['status'])
                ->latest()
                ->paginate(paginateNumber())
                ->through(
                    fn($campaign) => tap($campaign)
                        ->setRelation(
                            'accounts',
                            $campaign->posts->pluck('account')->unique('id')->values()
                        )
                        ->setAttribute('posts_count', $campaign->posts->count())
                        ->setAttribute('reach', $campaign->posts->sum(fn($post) => $post->reach ?? 0))
                        ->setAttribute('engagement', $campaign->posts->sum(fn($post) => $post->engagement ?? 0))
                ),
            'AnalyticalData' => $this->analyticsService->getAnalytics(),
        ]);



    }

    public function create()
    {
        $media = $this->user->files()
            ->where('type', FileKey::GALLERY_FILE->value)
            ->with('platforms.platform')
            ->get()
            ->map(fn($file) => [
                'id' => $file->id,
                'title' => $file->name,
                'type' => optional($file->platforms->first())->type,
                'size' => $file->size,
                'date' => $file->created_at->format('d F Y, h:i A'),
                'thumbnail' => imageURL($file, 'gallery'),
                'isVideo' => (getFileTypeFromExtension($file->extension) == 'video'),
                'platform' => optional($file->platforms->first()->platform)->slug,
                'alt' => $file->name
            ]);

        $templates = PostTemplate::where('user_id', auth()->id())
            ->search(['title'])
            ->filter(['platform_id'])
            ->with(['platform', 'files'])
            ->latest()
            ->get()
            ->map(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(),
            ]);

        $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()
            ->get();


        return Inertia::render("Campaign/Create", [
            "platforms" => Platform::all(),
            "accounts" => SocialAccount::with('platform')
                ->where('user_id', $this->user->id)
                ->where('workspace_id', $this->workspace->id)
                ->get(),
            'media' => $media,
            'post_templates' => $templates,
            'ai_templates' => $aiTemplates

        ]);
    }

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

        // Ensure user and workspace are available
        if (!$this->user) {
            return back()->with('error', 'User authentication failed. Please login again.');
        }

        if (!$this->workspace) {
            return back()->with('error', 'No workspace selected. Please select a workspace.');
        }

        // Debug: Log the validated data
        \Log::info('Campaign creation attempt', [
            'user_id' => $this->user->id,
            'workspace_id' => $this->workspace->id,
            'data' => $data
        ]);

        DB::beginTransaction();

        try {
            // --------------------------
            // Step 1: Create Campaign
            // --------------------------
            $campaign = Campaign::create([
                'user_id' => $this->user->id,
                'workspace_id' => $this->workspace->id,
                'name' => $data['campaignName'],
                'description' => $data['description'] ?? null,
                'start_date' => $data['startDate'] ?? null,
                'end_date' => $data['endDate'] ?? null,
                'repeat_every' => $data['repeat_every'] ?? 0,
                'repeat_end_date' => $data['repeat_end_date'] ?? null,
                'status' => StatusEnum::true->status(),
            ]);

            // --------------------------
            // Step 2: Save Posts (via PostManager)
            // --------------------------
            $data['campaign_id'] = $campaign->id;

            $this->savePosts($data, $this->user);

            DB::commit();

            return redirect()
                ->route("user.campaign.index")
                ->with('success', 'Campaign and posts created successfully!');
        } catch (\Exception $e) {
            DB::rollBack();

            // Log detailed error information
            \Log::error('Campaign creation failed', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
                'data' => $data
            ]);

            // Provide more specific error messages
            $errorMessage = 'Something went wrong while creating the campaign.';

            if (str_contains($e->getMessage(), 'schedule_time')) {
                $errorMessage = 'There was an issue with the scheduled time. Please check your scheduling settings.';
            } elseif (str_contains($e->getMessage(), 'account')) {
                $errorMessage = 'There was an issue with the selected accounts. Please verify your account selection.';
            } elseif (str_contains($e->getMessage(), 'validation')) {
                $errorMessage = 'Please check all required fields and try again.';
            } elseif (str_contains($e->getMessage(), 'database') || str_contains($e->getMessage(), 'SQL')) {
                $errorMessage = 'Database error occurred. Please try again later.';
            }

            return back()->with('error', $errorMessage . ' Error: ' . $e->getMessage());
        }
    }


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

        $campaign = Campaign::findOrFail($request->input('id'));
        $campaign->delete();

        return redirect()->route('user.campaign.index')->with('success', 'Campaign Deleted');

    }

    public function bulk(Request $request)
    {
        $validated = $request->validate([
            'action' => ['required', Rule::in(BulkActionEnum::values())],
            'ids' => 'required|array',
            'ids.*' => 'integer'
        ]);

        $query = SocialAccount::whereIn('id', $validated['ids']);

        match (BulkActionEnum::from($validated['action'])) {
            BulkActionEnum::ACTIVATE => $query->update(['status' => StatusEnum::true->status()]),
            BulkActionEnum::INACTIVATE => $query->update(['status' => StatusEnum::false->status()]),
            BulkActionEnum::DELETE => $query->delete(),
        };

        return back()->with('success', "Bulk {$validated['action']} completed.");
    }

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


        $campaign = tap(Campaign::with(['posts.account.platform', 'posts.files'])->findOrFail($id), function ($c) {
            $c->campaignData = [
                'id' => $c->id,
                'name' => $c->name,
                'start_date' => $c->start_date,
                'end_date' => $c->end_date,
                'description' => $c->description,
                'post_accounts' => $c->posts
                    ->map(fn($post) => $post->account)
                    ->unique('id')
                    ->values(),
                'post_types' => $c->posts->pluck('type')->unique()->values(),
                'content' => $c->posts->first()?->content,
                'files' => $c->posts->first()?->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' => $c->posts->first()?->links ?? [],
                'active_platform' => $c->active_platform ?? 'facebook',
                'is_scheduled' => $c->is_scheduled ?? '0',
                'scheduled_time' => $c->scheduled_time,
                'is_draft' => $c->is_draft ?? '0',
            ];
        });



        return Inertia::render('Campaign/Edit', [
            'campaign' => $campaign->campaignData,
            "platforms" => Platform::all(),
            "accounts" => SocialAccount::with('platform')
                ->where('user_id', $this->user->id)
                ->where('workspace_id', $this->workspace->id)
                ->get(),
            'media' => $media,
            'post_templates' => $templates,
            'ai_templates' => $aiTemplates,
        ]);

    }




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

        $campaign = Campaign::findOrFail($request->input('campaign_id'));

        DB::beginTransaction();

        try {
            // --------------------------
            // Step 1: Update Campaign
            // --------------------------
            $campaign->update([
                'name' => $data['campaignName'],
                'description' => $data['description'] ?? null,
                'start_date' => $data['startDate'] ?? null,
                'end_date' => $data['endDate'] ?? null,
                'repeat_every' => $data['repeat_every'] ?? 0,
                'repeat_end_date' => $data['repeat_end_date'] ?? null,
                'status' => StatusEnum::true->status(),
            ]);

            // --------------------------
            // Step 2: Update Posts (via PostManager trait)
            // --------------------------
            $data['campaign_id'] = $campaign->id;

            $this->updatePosts($data, $this->user, $campaign);

            DB::commit();

            return redirect()
                ->route("user.campaign.index")
                ->with('success', 'Campaign and posts updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            return back()->with('error', 'Something went wrong while updating the campaign.');
        }
    }




}
