<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Seller;
use App\Models\Product;
use App\Models\Rfq;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    use \App\Traits\ImageUploadTrait;
    public function dashboard()
    {
        $stats = [
            'users' => User::count(),
            'sellers' => Seller::count(),
            'products' => Product::count(),
            'rfqs' => Rfq::count(),
        ];

        // Fetch Recent Activity
        $recentUsers = User::latest()->take(5)->get()->map(function ($item) {
            $item->type = 'user';
            return $item;
        });

        $recentSellers = Seller::with('user')->latest()->take(5)->get()->map(function ($item) {
            $item->type = 'seller';
            return $item;
        });

        $recentProducts = Product::with('seller.user')->latest()->take(5)->get()->map(function ($item) {
            $item->type = 'product';
            return $item;
        });

        $recentRfqs = Rfq::with('buyer.user')->latest()->take(5)->get()->map(function ($item) {
            $item->type = 'rfq';
            return $item;
        });

        $recentActivity = $recentUsers->concat($recentSellers)
            ->concat($recentProducts)
            ->concat($recentRfqs)
            ->sortByDesc('created_at')
            ->take(10);

        return view('admin.dashboard', compact('stats', 'recentActivity'));
    }

    public function users(Request $request)
    {
        $query = User::query();

        // Search
        if ($request->has('q')) {
            $search = $request->q;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // Filter by Role
        if ($request->has('role') && $request->role != 'all') {
            $query->role($request->role);
        }

        // Filter by Status
        if ($request->has('status') && $request->status != 'all') {
            $status = $request->status == 'active' ? 1 : 0;
            $query->where('is_active', $status);
        }

        $users = $query->latest()->paginate(20);

        // Stats
        $totalUsers = User::count();
        $activeUsers = User::where('is_active', true)->count();
        $bannedUsers = User::where('is_active', false)->count();
        $newUsersToday = User::whereDate('created_at', today())->count();

        return view('admin.users.index', compact('users', 'totalUsers', 'activeUsers', 'bannedUsers', 'newUsersToday'));
    }

    public function toggleUserStatus(User $user)
    {
        $user->is_active = !$user->is_active;
        $user->save();

        $status = $user->is_active ? 'activated' : 'banned';
        return redirect()->back()->with('success', "User has been {$status}.");
    }

    public function storeUser(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8',
            'role' => 'required|in:seller,buyer,admin',
            'is_active' => 'boolean',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => \Illuminate\Support\Facades\Hash::make($request->password),
            'role' => $request->role,
            'is_active' => $request->is_active ?? true,
        ]);

        // Assign Role
        $role = \Spatie\Permission\Models\Role::where('name', $request->role)->first();
        if ($role) {
            $user->assignRole($role);
        }

        // Create Profile based on role
        if ($request->role === 'seller') {
            Seller::create(['user_id' => $user->id]);
        } elseif ($request->role === 'buyer') {
            \App\Models\Buyer::create(['user_id' => $user->id]);
        }

        return redirect()->back()->with('success', 'User created successfully.');
    }

    public function bulkAction(Request $request)
    {
        $userIds = $request->input('selected_users', []);
        $action = $request->input('action');

        if (empty($userIds)) {
            return redirect()->back()->with('error', 'No users selected.');
        }

        if ($action == 'delete') {
            $count = 0;
            foreach ($userIds as $id) {
                $user = User::find($id);
                if ($user) {
                    $this->forceDeleteUser($user);
                    $count++;
                }
            }
            return redirect()->back()->with('success', "$count users and all related data deleted successfully.");
        } elseif ($action == 'ban') {
            User::whereIn('id', $userIds)->update(['is_active' => false]);
            return redirect()->back()->with('success', 'Selected users banned successfully.');
        } elseif ($action == 'activate') {
            User::whereIn('id', $userIds)->update(['is_active' => true]);
            return redirect()->back()->with('success', 'Selected users activated successfully.');
        }

        return redirect()->back();
    }

    public function editUser($id)
    {
        $user = User::findOrFail($id);
        $roles = \Spatie\Permission\Models\Role::all();
        return view('admin.users.edit', compact('user', 'roles'));
    }

    public function updateUser(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8',
            'role' => 'required|exists:roles,name',
            'is_active' => 'boolean',
        ]);

        $data = [
            'name' => $request->name,
            'email' => $request->email,
            'is_active' => $request->is_active ?? true,
        ];

        if ($request->filled('password')) {
            $data['password'] = \Illuminate\Support\Facades\Hash::make($request->password);
        }

        $user->update($data);

        // Sync Roles
        $user->syncRoles([$request->role]);

        // If role changed to Seller/Buyer, ensure profile exists
        if ($request->role === 'seller' && !$user->seller) {
            Seller::create(['user_id' => $user->id]);
        } elseif ($request->role === 'buyer' && !$user->buyer) {
            \App\Models\Buyer::create(['user_id' => $user->id]);
        }

        return redirect()->route('admin.users')->with('success', 'User updated successfully.');
    }

    public function sellers(Request $request)
    {
        $query = Seller::with('user', 'subscription', 'plan');

        // Search
        if ($request->has('q')) {
            $search = $request->q;
            $query->where(function($q) use ($search) {
                $q->where('company_name', 'like', "%{$search}%")
                  ->orWhereHas('user', function($u) use ($search) {
                      $u->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by Status
        if ($request->has('status') && $request->status != 'all') {
            if ($request->status == 'verified') {
                $query->where('is_verified', true);
            } elseif ($request->status == 'pending') {
                $query->where('is_verified', false);
            }
        }

        // Filter by Subscription
        if ($request->has('plan') && $request->plan != 'all') {
            $query->whereHas('subscription', function($q) use ($request) {
                $q->where('plan_id', $request->plan);
            });
        }

        $sellers = $query->latest()->paginate(20);

        // Stats
        $totalSellers = Seller::count();
        $verifiedSellers = Seller::where('is_verified', true)->count();
        $pendingSellers = Seller::where('is_verified', false)->count();
        $newSellersToday = Seller::whereDate('created_at', today())->count();
        
        $plans = \App\Models\Plan::all();

        return view('admin.sellers.index', compact('sellers', 'totalSellers', 'verifiedSellers', 'pendingSellers', 'newSellersToday', 'plans'));
    }

    public function verifySeller($id)
    {
        $seller = Seller::findOrFail($id);
        $seller->update(['is_verified' => true]);

        // Send Email Notification
        \App\Services\EmailService::send('seller-verified', $seller->user->email, [
            'name' => $seller->user->name,
            'company_name' => $seller->company_name,
        ]);
        
        return redirect()->back()->with('success', 'Seller KYC verified successfully.');
    }

    public function revokeSeller($id)
    {
        $seller = Seller::findOrFail($id);
        $seller->update([
            'is_verified' => false,
            'kyc_status' => 'rejected' // Or pending, but rejected forces them to re-check
        ]);

        // Note: We might want to notify them
        // \App\Services\EmailService::send('seller-unverified', ...);

        return redirect()->back()->with('success', 'Seller verification revoked.');
    }

    public function rejectSeller(Request $request, $id)
    {
        $seller = Seller::findOrFail($id);
        // Logic to reject (maybe set is_verified to false if it was true, or just notify)
        // For now, we assume rejection means staying unverified but maybe adding a note (if we had a notes column)
        // Or we could delete the documents to force re-upload.
        
        // For this implementation, we'll just flash a message as "Rejected" usually implies asking for re-submission.
        // In a real app, we might want a 'rejection_reason' column.
        
        // Send Email Notification
        \App\Services\EmailService::send('seller-rejected', $seller->user->email, [
            'name' => $seller->user->name,
            'company_name' => $seller->company_name,
        ]);

        return redirect()->back()->with('error', 'Seller KYC rejected. Please contact the seller to re-submit documents.');
    }

    public function editSeller($id)
    {
        $seller = Seller::findOrFail($id);
        $units = \App\Models\Unit::where('is_active', true)->get();
        return view('admin.sellers.edit', compact('seller', 'units'));
    }

    public function updateSeller(Request $request, $id)
    {
        $seller = Seller::findOrFail($id);
        
        $request->validate([
            'moq_quantity' => 'required|integer|min:1',
            'moq_unit_id' => 'required|exists:units,id',
            'notification_enabled' => 'nullable|boolean',
            'microsite.tagline' => 'nullable|string|max:255',
            'microsite.years_in_business' => 'nullable|integer|min:0',
            'microsite.happy_clients' => 'nullable|integer|min:0',
            'microsite.products_sold' => 'nullable|integer|min:0',
            'microsite.cta_text' => 'nullable|string|max:50',
            'microsite.cta_link' => 'nullable|string|max:255',
        ]);

        // Update seller basic fields
        $updateData = [
            'moq_quantity' => $request->moq_quantity,
            'moq_unit_id' => $request->moq_unit_id,
        ];

        // Handle inquiry notification toggle (only for free sellers)
        // Paid sellers always have notifications enabled via canReceiveNotifications()
        if (!$seller->hasActiveSubscription()) {
            $updateData['notification_enabled'] = $request->has('notification_enabled') ? true : false;
        }

        $seller->update($updateData);

        // Update Microsite Settings
        if ($request->has('microsite')) {
            $micrositeData = $request->input('microsite');
            
            // Handle checkboxes (boolean fields)
            $booleans = ['show_stats', 'show_about', 'show_products', 'show_certificates', 'show_testimonials', 'show_faq', 'show_video', 'show_contact'];
            foreach ($booleans as $field) {
                $micrositeData[$field] = isset($micrositeData[$field]) ? true : false;
            }

            $seller->micrositeSettings()->updateOrCreate(
                ['seller_id' => $seller->id],
                $micrositeData
            );
        }

        return redirect()->route('admin.sellers')->with('success', 'Seller and microsite settings updated successfully.');
    }

    /**
     * Toggle seller active/inactive status
     */
    public function toggleSellerStatus(Seller $seller)
    {
        $seller->update(['is_active' => !$seller->is_active]);
        $status = $seller->is_active ? 'activated' : 'deactivated';
        return redirect()->back()->with('success', "Seller account {$status} successfully.");
    }

    /**
     * Permanently delete seller and all related data (2-step confirmation required)
     */
    /**
     * Schedule seller for deletion (Grace Period)
     */
    public function deleteSeller(Request $request, Seller $seller)
    {
        // If already requested, maybe force delete? For now, just schedule.
        // We will keep the confirmation code for safety, but change the message.
        
        $expectedCode = 'DELETE-' . $seller->id;
        
        $request->validate([
            'confirmation_code' => ['required', 'string', function ($attr, $value, $fail) use ($expectedCode) {
                if ($value !== $expectedCode) {
                    $fail('The confirmation code is incorrect. Enter "' . $expectedCode . '" to confirm.');
                }
            }],
        ]);

        $seller->update(['delete_requested_at' => now()]);
        
        $retentionPeriod = \App\Models\Setting::getValue('seller_retention_period', 3);

        return redirect()->route('admin.sellers')
            ->with('success', "Seller account scheduled for deletion. It will be permanently removed in {$retentionPeriod} months. You can restore it before then.");
    }

    /**
     * Restore a seller account scheduled for deletion
     */
    public function restoreSeller(Seller $seller)
    {
        $seller->update(['delete_requested_at' => null]);

        return redirect()->back()->with('success', 'Seller account deletion request has been cancelled. Account restored.');
    }

    /**
     * Helper to force delete a user and all related profiles/data
     */
    private function forceDeleteUser(User $user)
    {
        // 1. Delete Seller Profile & Data
        if ($user->hasRole('seller') && $user->seller) {
            $seller = $user->seller;
            
            // Delete all related data
            $seller->products()->delete();
            \App\Models\Inquiry::where('seller_id', $seller->id)->delete();
            \App\Models\Quote::where('seller_id', $seller->id)->delete();
            \App\Models\Transaction::where('seller_id', $seller->id)->delete();
            \App\Models\KycDocument::where('seller_id', $seller->id)->delete();
            \App\Models\KycActivityLog::where('seller_id', $seller->id)->delete();
            
            if (class_exists(\App\Models\Promotion::class)) {
                \App\Models\Promotion::where('seller_id', $seller->id)->delete();
            }
            
            if ($seller->micrositeSettings) $seller->micrositeSettings->delete();
            if ($seller->subscription) $seller->subscription->delete(); // Fixed: Delete Subscription
            
            \App\Models\Testimonial::where('seller_id', $seller->id)->delete();
            \App\Models\Faq::where('seller_id', $seller->id)->delete();
            \App\Models\SellerBanner::where('seller_id', $seller->id)->delete();
            
            $seller->delete();
        }

        // 2. Delete Buyer Profile & Data
        if ($user->hasRole('buyer') && $user->buyer) {
            $buyer = $user->buyer;
            $buyer->rfqs()->delete();
            $buyer->favorites()->delete();
            // Delete Saved Searches if exists
            if (method_exists($buyer, 'savedSearches')) $buyer->savedSearches()->delete();
            
            $buyer->delete();
        }

        // 3. Delete User
        $user->delete();
    }


    public function products(Request $request)
    {
        $query = Product::with('seller', 'category');

        // Search
        if ($request->has('q')) {
            $search = $request->q;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhereHas('seller', function($s) use ($search) {
                      $s->where('company_name', 'like', "%{$search}%");
                  });
            });
        }

        // Filter by Category
        if ($request->has('category') && $request->category != 'all') {
            $query->where('category_id', $request->category);
        }

        // Filter by Status
        if ($request->has('status') && $request->status != 'all') {
            if ($request->status == 'featured') {
                $query->where('is_highlighted', true);
            } elseif ($request->status == 'unfeatured') {
                $query->where('is_highlighted', false);
            }
        }

        $products = $query->latest()->paginate(20);

        // Stats
        $totalProducts = Product::count();
        $featuredProducts = Product::where('is_highlighted', true)->count();
        $newProductsToday = Product::whereDate('created_at', today())->count();
        
        $categories = \App\Models\Category::all();

        return view('admin.products.index', compact('products', 'totalProducts', 'featuredProducts', 'newProductsToday', 'categories'));
    }

    public function bulkProductAction(Request $request)
    {
        $productIds = $request->input('selected_products', []);
        $action = $request->input('action');

        if (empty($productIds)) {
            return redirect()->back()->with('error', 'No products selected.');
        }

        if ($action == 'delete') {
            Product::whereIn('id', $productIds)->delete();
            return redirect()->back()->with('success', 'Selected products deleted successfully.');
        } elseif ($action == 'feature') {
            Product::whereIn('id', $productIds)->update(['is_highlighted' => true]);
            return redirect()->back()->with('success', 'Selected products marked as featured.');
        } elseif ($action == 'unfeature') {
            Product::whereIn('id', $productIds)->update(['is_highlighted' => false]);
            return redirect()->back()->with('success', 'Selected products removed from featured.');
        }

        return redirect()->back();
    }

    public function toggleFeatured($id)
    {
        $product = Product::findOrFail($id);
        $product->update(['is_highlighted' => !$product->is_highlighted]);
        $status = $product->is_highlighted ? 'featured' : 'unfeatured';
        return redirect()->back()->with('success', "Product marked as $status.");
    }

    public function approveProduct($id)
    {
        $product = Product::findOrFail($id);
        $product->update(['is_approved' => true]);

        // Send Email Notification
        \App\Services\EmailService::send('product-approved', $product->seller->user->email, [
            'name' => $product->seller->user->name,
            'product_name' => $product->name,
        ]);

        // Send In-App Notification
        \App\Services\NotificationService::productApproved($product->seller->user->id, $product->name);

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

    public function rejectProduct(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        
        $request->validate([
            'rejection_reason' => 'required|string|max:255',
        ]);

        // Send Email Notification
        \App\Services\EmailService::send('product-rejected', $product->seller->user->email, [
            'name' => $product->seller->user->name,
            'product_name' => $product->name,
            'reason' => $request->rejection_reason,
        ]);

        // Send In-App Notification
        \App\Services\NotificationService::productRejected(
            $product->seller->user->id, 
            $product->name, 
            $request->rejection_reason
        );

        $product->update(['is_approved' => false]);
        
        return redirect()->back()->with('success', 'Product rejected and email sent to seller.');
    }

    public function editProduct($id)
    {
        $product = Product::findOrFail($id);
        $categories = \App\Models\Category::all();
        return view('admin.products.edit', compact('product', 'categories'));
    }

    public function updateProduct(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        
        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'description' => 'required|string',
            'price' => 'required|numeric|min:0',
            'moq' => 'required|integer|min:1',
            'images.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ]);

        $data = $request->only(['name', 'category_id', 'description', 'price', 'moq']);
        
        // Handle image deletion if passed
        if ($request->has('delete_images')) {
            $indicesToDelete = $request->delete_images;
            $newImagesJson = [];
            $imagesJson = $product->images_json ?? []; // Ensure it's an array

            foreach ($imagesJson as $index => $img) {
                if (in_array($index, $indicesToDelete)) {
                    // Check if it's an array (new structure) or string (old structure)
                    if (is_array($img)) {
                         if (isset($img['original'])) $this->deleteImage($img['original']);
                         if (isset($img['thumbnail'])) $this->deleteImage($img['thumbnail']);
                    } else {
                        $this->deleteImage($img);
                    }
                } else {
                    $newImagesJson[] = $img;
                }
            }
            $data['images_json'] = $newImagesJson;
        } else {
             // If no deletion, preserve existing images (unless overwritten by new upload logic which appends)
             // The logic below appends new images to existing ones.
             // If we deleted some, $data['images_json'] is already set to the filtered list.
             // If we didn't delete any, we need to start with the current list.
             if (!isset($data['images_json'])) {
                 $data['images_json'] = $product->images_json ?? [];
             }
        }

        // Handle New Images
        if ($request->hasFile('images')) {
            // $data['images_json'] is now either the filtered list (after deletion) or the original list
            $currentImages = $data['images_json'] ?? ($product->images_json ?? []);
            
            foreach ($request->file('images') as $image) {
                // Use ImageUploadTrait if available, or manual storage
                // Assuming AdminController doesn't use the trait yet, let's check imports or use manual
                // The previous code used manual storage. Let's stick to that or use trait if imported.
                // AdminController DOES NOT use ImageUploadTrait in the file I read.
                // But I should probably use it for consistency if I can, or just store.
                // For now, simple store as before but with structure.
                
                $path = $image->store('products', 'public');
                $currentImages[] = [
                    'original' => $path,
                    'thumbnail' => $path, // No resize for now unless I add the trait
                ];
            }
            $data['images_json'] = $currentImages;
        }

        $product->update($data);

        return redirect()->route('admin.products')->with('success', 'Product updated successfully.');
    }

    public function deleteProduct($id)
    {
        $product = Product::findOrFail($id);
        $product->delete();
        return redirect()->back()->with('success', 'Product deleted.');
    }

    public function rfqs(Request $request)
    {
        $query = Rfq::with('buyer');

        // Search
        if ($request->has('q')) {
            $search = $request->q;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhereHas('buyer', function($b) use ($search) {
                      $b->whereHas('user', function($u) use ($search) {
                          $u->where('name', 'like', "%{$search}%");
                      });
                  });
            });
        }

        // Filter by Status
        if ($request->has('status') && $request->status != 'all') {
            $query->where('status', $request->status);
        }

        $rfqs = $query->latest()->paginate(20);

        // Stats
        $totalRfqs = Rfq::count();
        $openRfqs = Rfq::where('status', 'open')->count();
        $closedRfqs = Rfq::where('status', 'closed')->count();
        $newRfqsToday = Rfq::whereDate('created_at', today())->count();

        return view('admin.rfqs.index', compact('rfqs', 'totalRfqs', 'openRfqs', 'closedRfqs', 'newRfqsToday'));
    }

    public function deleteRfq($id)
    {
        $rfq = Rfq::findOrFail($id);
        $rfq->delete();
        return redirect()->back()->with('success', 'RFQ deleted successfully.');
    }

    public function impersonate($userId)
    {
        $user = User::findOrFail($userId);
        
        // Prevent impersonating yourself or other admins if needed (optional)
        if ($user->id === auth()->id()) {
            return redirect()->back()->with('error', 'You cannot impersonate yourself.');
        }

        // Store original admin id
        session()->put('impersonate', auth()->id());

        // Login as user
        auth()->login($user);

        // Redirect based on role
        if ($user->hasRole('seller')) {
            return redirect()->route('seller.dashboard')->with('success', "You are now impersonating {$user->name}.");
        } elseif ($user->hasRole('buyer')) {
            return redirect()->route('buyer.dashboard')->with('success', "You are now impersonating {$user->name}.");
        } elseif ($user->hasRole('admin')) {
            return redirect()->route('admin.dashboard')->with('success', "You are now impersonating {$user->name}.");
        }

        return redirect('/')->with('success', "You are now impersonating {$user->name}.");
    }

    public function stopImpersonating()
    {
        if (session()->has('impersonate')) {
            $adminId = session('impersonate');
            
            // Login back as admin
            auth()->loginUsingId($adminId);
            
            // Clear session
            session()->forget('impersonate');

            return redirect()->route('admin.dashboard')->with('success', 'Welcome back, Admin!');
        }

        return redirect()->route('admin.dashboard');
    }
}
