<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\KycDocument;
use App\Models\KycActivityLog;
use App\Models\Seller;
use Illuminate\Http\Request;

class KycController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->status ?? 'pending';
        
        $query = Seller::whereHas('kycDocuments') // Use correct relationship
                 ->with(['user', 'subscription.plan', 'kycDocuments']);
        
        // Filter by document status
        if ($status !== 'all') {
            $query->whereHas('kycDocuments', function($q) use ($status) {
                $q->where('status', $status);
            });
        }
        
        // Seller type filter (paid/free)
        if ($request->seller_type === 'paid') {
            $query->whereNotNull('subscription_id');
        } elseif ($request->seller_type === 'free') {
            $query->whereNull('subscription_id');
        }
        
        // Search
        if ($request->search) {
            $query->where(function($q) use ($request) {
                $q->where('company_name', 'like', "%{$request->search}%")
                  ->orWhereHas('user', fn($u) => $u->where('name', 'like', "%{$request->search}%"));
            });
        }
        
        // Final pagination
        $sellers = $query->latest('updated_at')->paginate(15)->withQueryString();
        
        // Stats
        $stats = [
            'pending' => KycDocument::where('status', 'pending')->count(),
            'approved' => KycDocument::where('status', 'approved')->count(),
            'rejected' => KycDocument::where('status', 'rejected')->count(),
        ];
        
        return view('admin.kyc.index', compact('sellers', 'stats', 'status'));
    }

    public function show(Seller $seller)
    {
        $seller->load(['user', 'subscription.plan']);
        $documents = KycDocument::where('seller_id', $seller->id)->get();
        $activities = KycActivityLog::where('seller_id', $seller->id)
            ->with(['actor', 'document'])
            ->latest()
            ->get();
        
        return view('admin.kyc.show', compact('seller', 'documents', 'activities'));
    }

    public function approve(KycDocument $document)
    {
        $document->update(['status' => 'approved']);

        // Log activity
        KycActivityLog::create([
            'seller_id' => $document->seller_id,
            'kyc_document_id' => $document->id,
            'action' => 'approved',
            'actor_type' => 'admin',
            'actor_id' => auth()->id(),
            'notes' => 'Document approved by admin.',
        ]);

        // If GST, Incorporation, PAN, or Photo, verify the seller
        if (in_array($document->document_type, ['gst', 'incorporation', 'pan', 'photo'])) {
            $seller = $document->seller;
            $seller->update([
                'is_verified' => true,
                'kyc_status' => 'verified'
            ]);
            
            // Notify Seller via Email
            \App\Services\EmailService::send('seller-verified', $seller->user->email, [
                'name' => $seller->user->name,
            ]);

            // Notify Seller via In-App Notification
            \App\Services\NotificationService::kycApproved($seller->user->id);
        }

        return redirect()->back()->with('success', 'Document approved successfully.');
    }

    public function reject(Request $request, KycDocument $document)
    {
        $request->validate([
            'rejection_reason' => 'required|string|max:500',
        ]);

        $document->update([
            'status' => 'rejected',
            'rejection_reason' => $request->rejection_reason,
        ]);

        // Log activity
        KycActivityLog::create([
            'seller_id' => $document->seller_id,
            'kyc_document_id' => $document->id,
            'action' => 'rejected',
            'actor_type' => 'admin',
            'actor_id' => auth()->id(),
            'notes' => $request->rejection_reason,
        ]);

        // Notify Seller via Email
        \App\Services\EmailService::send('kyc-rejected', $document->seller->user->email, [
            'name' => $document->seller->user->name,
            'document_type' => strtoupper($document->document_type),
            'reason' => $request->rejection_reason,
        ]);

        // Notify Seller via In-App Notification
        \App\Services\NotificationService::kycRejected(
            $document->seller->user->id, 
            $request->rejection_reason
        );

        return redirect()->back()->with('success', 'Document rejected.');
    }

    public function resetToPending(KycDocument $document)
    {
        $document->update(['status' => 'pending']);

        // Log activity
        KycActivityLog::create([
            'seller_id' => $document->seller_id,
            'kyc_document_id' => $document->id,
            'action' => 'reset_to_pending',
            'actor_type' => 'admin',
            'actor_id' => auth()->id(),
            'notes' => 'Document status reset to pending by admin.',
        ]);

        // If this was a core doc that made the seller verified, reset verification status
        $seller = $document->seller;
        if (in_array($document->document_type, ['gst', 'incorporation', 'pan', 'photo'])) {
            if ($seller->kyc_status === 'verified') {
                $seller->update([
                    'is_verified' => false,
                    'kyc_status' => 'submitted'
                ]);
            }
        }

        return redirect()->back()->with('success', 'Document status reset to pending.');
    }

    public function bulkApprove(Request $request)
    {
        $request->validate([
            'document_ids' => 'required|array|min:1',
            'document_ids.*' => 'exists:kyc_documents,id',
        ]);

        $documents = KycDocument::whereIn('id', $request->document_ids)->get();
        $count = 0;

        foreach ($documents as $document) {
            if ($document->status === 'pending') {
                $document->update(['status' => 'approved']);
                
                // Log activity
                KycActivityLog::create([
                    'seller_id' => $document->seller_id,
                    'kyc_document_id' => $document->id,
                    'action' => 'approved',
                    'actor_type' => 'admin',
                    'actor_id' => auth()->id(),
                    'notes' => 'Bulk approval by admin.',
                ]);

                // If GST, Incorporation, PAN, or Photo, verify the seller
                if (in_array($document->document_type, ['gst', 'incorporation', 'pan', 'photo'])) {
                    $seller = $document->seller;
                    $seller->update([
                        'is_verified' => true,
                        'kyc_status' => 'verified'
                    ]);
                    
                    \App\Services\EmailService::send('seller-verified', $seller->user->email, [
                        'name' => $seller->user->name,
                    ]);
                    \App\Services\NotificationService::kycApproved($seller->user->id);
                }
                
                $count++;
            }
        }

        return redirect()->back()->with('success', "{$count} document(s) approved successfully.");
    }

    public function bulkReject(Request $request)
    {
        $request->validate([
            'document_ids' => 'required|array|min:1',
            'document_ids.*' => 'exists:kyc_documents,id',
            'rejection_reason' => 'required|string|max:500',
        ]);

        $documents = KycDocument::whereIn('id', $request->document_ids)->get();
        $count = 0;

        foreach ($documents as $document) {
            if ($document->status === 'pending') {
                $document->update([
                    'status' => 'rejected',
                    'rejection_reason' => $request->rejection_reason,
                ]);
                
                // Log activity
                KycActivityLog::create([
                    'seller_id' => $document->seller_id,
                    'kyc_document_id' => $document->id,
                    'action' => 'rejected',
                    'actor_type' => 'admin',
                    'actor_id' => auth()->id(),
                    'notes' => $request->rejection_reason,
                ]);

                // Notify Seller
                \App\Services\EmailService::send('kyc-rejected', $document->seller->user->email, [
                    'name' => $document->seller->user->name,
                    'document_type' => strtoupper($document->document_type),
                    'reason' => $request->rejection_reason,
                ]);
                \App\Services\NotificationService::kycRejected(
                    $document->seller->user->id, 
                    $request->rejection_reason
                );
                
                $count++;
            }
        }

        return redirect()->back()->with('success', "{$count} document(s) rejected.");
    }
}
