<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\ReferralLead;
use App\Models\ReferralCommission;
use App\Models\ReferralPayout;
use App\Models\ReferralSetting;
use App\Http\Controllers\Traits\EmailTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class AdminReferralController extends Controller
{
    use EmailTrait;

    /**
     * Admin Approves Payout
     */
    public function approvePayout(Request $request, $payoutId)
    {
        $validator = Validator::make($request->all(), [
            'action' => 'required|in:approve,reject',
            'attachment' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->errorWithData($validator->errors(), 'Validation failed', 422);
        }

        try {
            $payout = ReferralPayout::with('referralUser')->find($payoutId);
            
            if (!$payout) {
                return $this->error('Payout request not found', 404);
            }

            $attachmentUrl = null;
            
            if ($request->hasFile('attachment')) {
                $path = $request->file('attachment')->store('referral-payouts', 'public');
                $attachmentUrl = Storage::url($path);
            }

            if ($request->action === 'approve') {
                $payout->approve($attachmentUrl, $request->notes, auth()->id());
                
                // Send notification to referral user about payout approval
                $this->save_notifications(
                    'Payout Approved',
                    'Your payout request of $' . number_format($payout->amount, 2) . ' has been approved and processed.',
                    config('constants.employee_types.admin'),
                    config('constants.superadmin'),
                    config('constants.employee_types.customer'),
                    $payout->referral_user_id,
                    'payout_approved'
                );
                
                $message = 'Payout approved and processed successfully';
            } else {
                $payout->reject($request->notes, auth()->id());
                
                // Send notification to referral user about payout rejection
                $this->save_notifications(
                    'Payout Rejected',
                    'Your payout request of $' . number_format($payout->amount, 2) . ' has been rejected. ' . ($request->notes ? 'Reason: ' . $request->notes : ''),
                    config('constants.employee_types.admin'),
                    config('constants.superadmin'),
                    config('constants.employee_types.customer'),
                    $payout->referral_user_id,
                    'payout_rejected'
                );
                
                $message = 'Payout request rejected';
            }

            return $this->success($payout, $message);

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    /**
     * Admin Settings
     */
    public function updateSettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'commission_type' => 'required|in:percentage,fixed',
            'commission_value' => 'required|numeric|min:0',
            'payout_threshold' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->errorWithData($validator->errors(), 'Validation failed', 422);
        }

        try {
            // Deactivate current settings
            ReferralSetting::where('is_active', true)->update(['is_active' => false]);
            
            // Create new settings
            $settings = ReferralSetting::create([
                'commission_type' => $request->commission_type,
                'commission_value' => $request->commission_value,
                'payout_threshold' => $request->payout_threshold,
                'is_active' => true,
            ]);

            return $this->success($settings, 'Referral settings updated successfully');

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    /**
     * Get Referral Users
     */
    public function getReferralUsers(Request $request, $referred_by)
    {
        $user = User::find($referred_by);
        $referralCommissionsTable = $user->referralCommissions()
        ->with(['customer', 'commissionPayouts.payout'])
        ->latest()
        ->get()
        ->map(function ($commission) {
            // Check if commission is included in any payout
            $isInPayout = $commission->isIncludedInPayout();
            $payoutStatus = 'Available for Payout';
            $payoutId = null;
            
            if ($isInPayout) {
                $commissionPayout = $commission->commissionPayouts()
                    ->whereIn('status', ['requested', 'completed'])
                    ->with('payout')
                    ->first();
                
                if ($commissionPayout) {
                    $payoutId = $commissionPayout->payout_id;
                    switch ($commissionPayout->status) {
                        case 'requested':
                            $payoutStatus = 'In Payout Request';
                            break;
                        case 'completed':
                            $payoutStatus = 'Paid Out';
                            break;
                    }
                }
            }

            return [
                'commission_id' => $commission->id,
                'customer_name' => $commission->customer->name ?? 'N/A',
                'customer_email' => $commission->customer->email ?? 'N/A',
                'order_date' => $commission->created_at,
                'order_amount' => number_format($commission->plan_price, 2),
                'commission_rate' => $commission->commission_rate . '%',
                'your_payout' => number_format($commission->commission_amount, 2),
                'status' => ucfirst($commission->status),
                'payout_status' => $payoutStatus,
                'action' => $commission->status === 'approved' && !$isInPayout ? 'Available for Payout' : 
                           ($commission->status === 'paid' ? 'Paid' : 'Pending Approval'),
                'order_id' => $commission->order_id,
                'payout_id' => $payoutId,
            ];
        });
        return $this->success($referralCommissionsTable, 'Referral users loaded successfully');
    }
    /**
     * Get Admin Dashboard Data
     */
    public function adminDashboard(Request $request)
    {
        try {
            $totalReferralUsers = User::whereIn('user_type', [2, 4])->whereNotNull('referral_code')->count();
            $activeReferralUsers = User::whereIn('user_type', [2, 4])->whereNotNull('referral_code')->where('status', 'active')->count();
            $pendingReferralUsers = User::whereIn('user_type', [2, 4])->whereNotNull('referral_code')->where('status', 'pending')->count();

            $totalReferrals = User::whereNotNull('referred_by')->count();

            $totalLeads = ReferralLead::count();
            $convertedLeads = ReferralLead::where('status', 'converted')->count();

            $totalCommissions = ReferralCommission::sum('commission_amount');
            $pendingCommissions = ReferralCommission::where('status', 'pending')->sum('commission_amount');
            $approvedCommissions = ReferralCommission::where('status', 'approved')->sum('commission_amount');

            $totalPayouts = ReferralPayout::sum('amount');
            $pendingPayouts = ReferralPayout::where('status', 'requested')->sum('amount');
            $paidPayouts = ReferralPayout::where('status', 'paid')->sum('amount');

            // Top referrers by referral count
            $topReferrers = User::whereNotNull('referral_code')
                ->withCount('referrals')
                ->orderBy('referrals_count', 'desc')
                ->limit(10)
                ->get()
                ->map(function ($user) {
                    return [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'referral_code' => $user->referral_code,
                        'referred_by' => $user->referred_by,
                        'referral_code_used' => $user->referral_code_used,
                        'status' => $user->status,
                        'user_type' => $user->user_type,
                        'referrals_count' => $user->referrals_count,
                        'referral_link' => 'https://staging.workforcems.com.au/admin-signup?ref=' . $user->referral_code,
                    ];
                });

            // Recent activities
            $settings = ReferralSetting::getActive();
            $commissionRate = $settings ? $settings->commission_value : 0;

            $recentReferralSignups = User::whereIn('user_type', [2, 4])
                ->whereNotNull('referred_by')
                ->with('referrer:id,name,email')
                ->latest()
                ->limit(5)
                ->get(['id', 'name', 'email', 'status', 'created_at', 'referred_by'])
                ->map(function ($user) use ($commissionRate) {
                    $user->commission_rate = $commissionRate;
                    return $user;
                });

            $recentPayoutRequests = ReferralPayout::with('referralUser:id,name,email')
                ->where('status', 'requested')
                ->latest()
                ->get();
            $payoutsHistory = ReferralPayout::with('referralUser:id,name,email')
            ->whereIn('status', ['paid', 'rejected'])
            ->latest()
            ->get();
            $data = [
                    'stats' => [
                        'total_referral_users' => $totalReferralUsers,
                        'active_referral_users' => $activeReferralUsers,
                        'pending_referral_users' => $pendingReferralUsers,
                        'total_referrals' => $totalReferrals,
                        'total_leads' => $totalLeads,
                        'converted_leads' => $convertedLeads,
                        'conversion_rate' => $totalLeads > 0 ? round(($convertedLeads / $totalLeads) * 100, 2) : 0,
                        'total_commissions' => $totalCommissions,
                        'pending_commissions' => $pendingCommissions,
                        'approved_commissions' => $approvedCommissions,
                        'total_payouts' => $totalPayouts,
                        'pending_payouts' => $pendingPayouts,
                        'paid_payouts' => $paidPayouts,
                    ],
                    'top_referrers' => $topReferrers,
                    'recent_payout_requests' => $recentPayoutRequests,
                    'payouts_history' => $payoutsHistory,
                ];
            return $this->success($data, 'Admin dashboard loaded successfully');

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    /**
     * Get Detailed Payout Information
     */
    public function getPayoutDetails($payoutId)
    {
        try {
            $payout = ReferralPayout::with([
                'referralUser:id,name,email,mobile_number',
                'commissions.customer:id,name,email',
                'commissionPayouts.commission',
                'processedBy:id,name,email'
            ])->find($payoutId);

            if (!$payout) {
                return $this->error('Payout request not found', 404);
            }

            // Format commission details
            $commissionDetails = $payout->commissionPayouts->map(function ($cp) {
                return [
                    'id' => $cp->id,
                    'commission_id' => $cp->commission_id,
                    'amount' => $cp->commission_amount,
                    'status' => $cp->status,
                    'included_at' => $cp->included_at,
                    'processed_at' => $cp->processed_at,
                    'notes' => $cp->notes,
                    'customer' => [
                        'id' => $cp->commission->customer->id,
                        'name' => $cp->commission->customer->name,
                        'email' => $cp->commission->customer->email,
                    ],
                    'order_id' => $cp->commission->order_id,
                    'plan_price' => $cp->commission->plan_price,
                    'commission_rate' => $cp->commission->commission_rate,
                ];
            });

            $payout->commission_details = $commissionDetails;
            $payout->commission_count = $payout->getCommissionCount();
            $payout->total_commission_amount = $payout->getTotalCommissionAmount();

            return $this->success($payout, 'Payout details loaded successfully');

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    /**
     * Get Current Settings
     */
    public function getSettings()
    {
        try {
            $settings = ReferralSetting::getActive();
            
            return $this->success($settings, 'Settings loaded successfully');

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }
}
