<?php

namespace App\Http\Controllers;

use App\Enums\AccountType;
use App\Enums\BulkActionEnum;
use App\Enums\StatusEnum;
use App\Models\SocialAccount;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

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

    use Fileable, ModelAction;

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

    public function index(Request $request)
    {
        // Check user filter preference (default to 'mine' for non-admin users)
        $userFilter = $request->get('user_filter', 'mine');

        // Base query with user relations
        $query = SocialAccount::with(['platform', 'user'])
            ->when($userFilter === 'mine', function ($query) {
                $query->where('user_id', $this->user->id);
            })
            ->when($userFilter === 'others', function ($query) {
                $query->where('user_id', '!=', $this->user->id);
            })
            // 'all' shows everything - no additional filtering needed
            ->when($request->platform, function ($query) use ($request) {
                $query->whereHas('platform', function ($q) use ($request) {
                    $q->where('slug', $request->platform);
                });
            })
            ->when($request->status, function ($query) use ($request) {
                $query->where('status', $request->status);
            })
            ->when($request->search, function ($query) use ($request) {
                $query->where(function ($q) use ($request) {
                    $q->where('name', 'like', '%' . $request->search . '%')
                      ->orWhere('label', 'like', '%' . $request->search . '%')
                      ->orWhereHas('user', function ($userQuery) use ($request) {
                          $userQuery->where('name', 'like', '%' . $request->search . '%')
                                   ->orWhere('email', 'like', '%' . $request->search . '%');
                      });
                });
            })
            ->latest();

        $accounts = $query->paginate(12);
        $platforms = \App\Models\Platform::active()->get();

        // Get account counts for admin dashboard (both global and platform-specific)
        $accountCounts = [
            'global' => [
                'mine' => SocialAccount::where('user_id', $this->user->id)->count(),
                'others' => SocialAccount::where('user_id', '!=', $this->user->id)->count(),
                'all' => SocialAccount::count(),
            ]
        ];

        // Add platform-specific counts
        foreach ($platforms as $platform) {
            $accountCounts['platforms'][$platform->slug] = [
                'mine' => SocialAccount::where('user_id', $this->user->id)
                    ->whereHas('platform', function ($q) use ($platform) {
                        $q->where('slug', $platform->slug);
                    })->count(),
                'others' => SocialAccount::where('user_id', '!=', $this->user->id)
                    ->whereHas('platform', function ($q) use ($platform) {
                        $q->where('slug', $platform->slug);
                    })->count(),
                'all' => SocialAccount::whereHas('platform', function ($q) use ($platform) {
                    $q->where('slug', $platform->slug);
                })->count(),
            ];
        }

        return inertia('Accounts/Index', [
            'accounts' => $accounts,
            'platforms' => $platforms,
            'accountCounts' => $accountCounts,
            'currentUser' => $this->user,
            'filters' => $request->only(['platform', 'status', 'search', 'user_filter'])
        ]);
    }

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

        try {
            $workspace = SocialAccount::findOrFail($request->id);
            $workspace->status = $request->status;
            $workspace->save();

            return back()->with('success', 'Account status updated successfully');
        } catch (\Exception $e) {
            return back()->with('error', 'Account status did not change');

        }
    }

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

        $socialAccount = SocialAccount::findOrFail($request->input('id'));
        $socialAccount->delete();

        return redirect()->route('user.platform.accounts', $socialAccount->platform_id)->with('success', 'Account 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 create(Request $request)
    {
        $account = SocialAccount::create([
            'label' => $request->input('label'),
            'platform_id' => $request->input('platform_id'),
            'user_id' => $this->user->id,
            'workspace_id' => $this->workspace->id,
            'account_type' => AccountType::PAGE->value,
            'is_connected' => StatusEnum::false->status()
        ]);

        session([
            'initiated_account_id' => $account->id,
            'user_id' => $this->user->id,
        ]);

        return redirect()->back();
    }

}
