<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\FbDailySetting;
use App\Models\FbSubmission;
use App\Models\User;
use App\Models\IncomeHistory;
use App\Models\BalanceLog;
use App\Models\Setting;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\FbSubmissionsExport;
use App\Exports\ProcessingSubmissionsExport;

class FbAdminController extends Controller
{
    public function export(Request $request)
    {
        $status = $request->input('status', 'pending');

        return Excel::download(new FbSubmissionsExport($status), "{$status}_submissions.xlsx");
    }

    public function exportProcessing()
    {
        return Excel::download(new ProcessingSubmissionsExport(), 'processing_submissions.xlsx');
    }

    public function settings()
    {
        $setting = FbDailySetting::effectiveForToday();
        $telegramLink = (string) (Setting::query()->where('key', 'facebook_sell_telegram_link')->value('value') ?? '');
        $cookieLinkEnabled = (int) (Setting::query()->where('key', 'facebook_sell_cookie_link_enabled')->value('value') ?? 1);

        return view('fb_admin.settings', compact('setting', 'telegramLink', 'cookieLinkEnabled'));
    }

    public function saveSettings(Request $request)
    {
        $request->validate([
            'password' => 'required',
            'amount_per_id' => 'required|numeric',
            'limit_per_user' => 'required|integer',
            'is_active' => 'nullable|in:0,1',
            'cookie_link_enabled' => 'nullable|in:0,1',
            'telegram_link' => 'nullable|string|max:255',
            'upline_commissions' => 'nullable|array',
            'upline_commissions.*' => 'nullable|numeric|min:0',
        ]);

        $telegramLink = trim((string) $request->input('telegram_link', ''));

        $commissions = collect($request->input('upline_commissions', []))
            ->filter(function ($v) {
                return $v !== null && $v !== '' && is_numeric($v);
            })
            ->map(fn ($v) => (float) $v)
            ->values()
            ->toArray();

        FbDailySetting::updateOrCreate(
            ['date' => now()->toDateString()],
            [
                'password' => $request->password,
                'amount_per_id' => $request->amount_per_id,
                'limit_per_user' => $request->limit_per_user,
                'is_active' => (int) $request->input('is_active', 0),
                'upline_commissions' => $commissions,
            ]
        );

        if ($telegramLink === '') {
            Setting::query()->where('key', 'facebook_sell_telegram_link')->delete();
        } else {
            Setting::updateOrCreate(
                ['key' => 'facebook_sell_telegram_link'],
                ['value' => $telegramLink]
            );
        }

        Setting::updateOrCreate(
            ['key' => 'facebook_sell_cookie_link_enabled'],
            ['value' => (string) ((int) $request->input('cookie_link_enabled', 0))]
        );

        return back()->with('success', 'সেটিংস আপডেট হয়েছে');
    }

    public function dashboard()
    {
        $submissions = FbSubmission::with('user')->latest()->get();

        return view('fb_admin.dashboard', compact('submissions'));
    }

    public function showByStatus(Request $request, $status)
    {
        $allowed = ['pending', 'approved', 'rejected', 'processing'];

        if (!in_array($status, $allowed, true)) {
            abort(404);
        }

        $query = FbSubmission::where('status', $status)->with('user');

        if ($request->filled('uids')) {
            $uids = preg_split('/[\s,]+/', (string) $request->uids, -1, PREG_SPLIT_NO_EMPTY);
            $query->whereIn('fb_uid', $uids);
        }

        $submissions = $query->latest()->paginate(15000);

        return view("fb_admin.status.$status", compact('submissions', 'status'));
    }

    public function bulkAction(Request $request)
    {
        $request->validate([
            'selected_ids'   => 'required|array|min:1',
            'selected_ids.*' => 'integer',
            'action'         => 'required|in:approved,rejected,processing,pending',
        ], [
            'selected_ids.required' => 'কমপক্ষে একটি সাবমিশন সিলেক্ট করুন।',
        ]);

        $ids = array_map('intval', $request->input('selected_ids', []));
        $action = $request->input('action');

        if ($action !== 'approved') {
            FbSubmission::whereIn('id', $ids)->update(['status' => $action]);

            return back()->with('success', 'Selected submissions updated successfully.');
        }

        $this->approveSubmissions($ids);

        return back()->with('success', 'Selected submissions updated successfully.');
    }

    public function changeStatus($id, $status)
    {
        if (!in_array($status, ['pending', 'processing', 'approved', 'rejected'], true)) {
            abort(404);
        }

        $this->applySingleStatus((int) $id, $status);

        return back()->with('success', 'Submission status updated successfully.');
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:pending,processing,approved,rejected',
        ]);

        $this->applySingleStatus((int) $id, (string) $request->status);

        return back()->with('success', 'Submission status updated successfully.');
    }

    private function applySingleStatus(int $id, string $status): void
    {
        if ($status !== 'approved') {
            FbSubmission::where('id', $id)->update(['status' => $status]);
            return;
        }

        $this->approveSubmissions([$id]);
    }

    private function approveSubmissions(array $ids): void
    {
        $setting = FbDailySetting::effectiveForToday();
        $amount = (float) ($setting->amount_per_id ?? 0.0);
        $commissions = $setting ? ($setting->upline_commissions ?? []) : [];
        $commissions = array_values(array_map('floatval', $commissions));

        DB::transaction(function () use ($ids, $amount, $commissions) {
            $subs = FbSubmission::whereIn('id', $ids)
                ->with('user')
                ->lockForUpdate()
                ->get();

            foreach ($subs as $sub) {
                $alreadyApproved = ($sub->status === 'approved');

                if (!$alreadyApproved && $amount > 0 && $sub->user) {
                    $user = $sub->user;

                    $user->increment('balance', $amount);

                    BalanceLog::create([
                        'user_id' => $user->id,
                        'amount' => $amount,
                    ]);

                    IncomeHistory::create([
                        'user_id' => $user->id,
                        'source' => 'fb_uid',
                        'amount' => $amount,
                        'description' => 'অভিনন্দন! আপনি Facebook UID সাবমিশন থেকে ' . $amount . '৳ ইনকাম পেয়েছেন।',
                    ]);

                    $level = 1;
                    $referrerCode = $user->referred_by;

                    foreach ($commissions as $commission) {
                        if (!$referrerCode) {
                            break;
                        }

                        $upline = User::where('referral_code', $referrerCode)->first();
                        if (!$upline) {
                            break;
                        }

                        $commission = (float) $commission;

                        if ($commission > 0) {
                            $upline->increment('balance', $commission);

                            BalanceLog::create([
                                'user_id' => $upline->id,
                                'amount' => $commission,
                            ]);

                            IncomeHistory::create([
                                'user_id' => $upline->id,
                                'source' => 'fb_uid_bonus',
                                'amount' => $commission,
                                'description' => "অভিনন্দন! আপনি {$level}য় লেভেলের UID সাবমিশন থেকে {$commission}৳ কমিশন পেয়েছেন।",
                            ]);
                        }

                        $referrerCode = $upline->referred_by;
                        $level++;
                    }
                }

                $sub->status = 'approved';
                $sub->save();
            }
        });
    }
}
