<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Inquiry;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InquiryController extends Controller
{
    public function index(Request $request)
    {
        $query = Inquiry::with(['seller.user', 'buyer.user', 'product', 'assignedBy']);

        // Filter by admin status
        if ($request->filled('admin_status') && $request->admin_status !== 'all') {
            $query->where('admin_status', $request->admin_status);
        } else {
            // Default to showing pending inquiries first
            $query->orderByRaw("CASE WHEN admin_status = 'pending' THEN 0 WHEN admin_status = 'assigned' THEN 1 ELSE 2 END");
        }

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

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

        // Filter by date range
        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->from_date);
        }
        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->to_date);
        }

        $inquiries = $query->latest()->paginate(20)->withQueryString();

        // Stats
        $stats = [
            'total' => Inquiry::count(),
            'pending' => Inquiry::where('admin_status', Inquiry::ADMIN_STATUS_PENDING)->count(),
            'assigned' => Inquiry::where('admin_status', Inquiry::ADMIN_STATUS_ASSIGNED)->count(),
            'rejected' => Inquiry::where('admin_status', Inquiry::ADMIN_STATUS_REJECTED)->count(),
            'today' => Inquiry::whereDate('created_at', today())->count(),
            'this_week' => Inquiry::whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])->count(),
        ];

        return view('admin.inquiries.index', compact('inquiries', 'stats'));
    }

    public function show(Inquiry $inquiry)
    {
        $inquiry->load(['seller.user', 'buyer.user', 'product', 'assignedBy']);
        
        return view('admin.inquiries.show', compact('inquiry'));
    }

    /**
     * Assign inquiry to seller (admin action)
     */
    public function assign(Request $request, Inquiry $inquiry)
    {
        $request->validate([
            'admin_notes' => 'nullable|string|max:500',
        ]);

        $inquiry->update([
            'admin_status' => Inquiry::ADMIN_STATUS_ASSIGNED,
            'assigned_by_admin_id' => Auth::id(),
            'assigned_at' => now(),
            'admin_notes' => $request->admin_notes,
        ]);

        // Notify seller if notifications are enabled
        if ($inquiry->seller->canReceiveNotifications()) {
            \App\Services\NotificationService::create(
                $inquiry->seller->user->id,
                'New Inquiry Assigned',
                "An inquiry from {$inquiry->name} has been assigned to you by admin.",
                route('seller.inquiries.index')
            );

            \App\Services\EmailService::send('inquiry-assigned', $inquiry->seller->user->email, [
                'seller_name' => $inquiry->seller->user->name,
                'buyer_name' => $inquiry->name,
                'product_name' => $inquiry->product->name ?? 'General Inquiry',
                'message' => $inquiry->message,
                'admin_notes' => $request->admin_notes,
                'link' => route('seller.inquiries.index'),
            ]);
        }

        return redirect()->back()->with('success', 'Inquiry assigned successfully!');
    }

    /**
     * Reject inquiry (admin action)
     */
    public function reject(Request $request, Inquiry $inquiry)
    {
        $request->validate([
            'admin_notes' => 'required|string|max:500',
        ]);

        $inquiry->update([
            'admin_status' => Inquiry::ADMIN_STATUS_REJECTED,
            'assigned_by_admin_id' => Auth::id(),
            'assigned_at' => now(),
            'admin_notes' => $request->admin_notes,
        ]);

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

    /**
     * Bulk assign inquiries
     */
    public function bulkAssign(Request $request)
    {
        $request->validate([
            'inquiry_ids' => 'required|array',
            'inquiry_ids.*' => 'exists:inquiries,id',
            'admin_notes' => 'nullable|string|max:500',
        ]);

        $updated = Inquiry::whereIn('id', $request->inquiry_ids)->update([
            'admin_status' => Inquiry::ADMIN_STATUS_ASSIGNED,
            'assigned_by_admin_id' => Auth::id(),
            'assigned_at' => now(),
            'admin_notes' => $request->admin_notes,
        ]);

        // Notify sellers for each inquiry
        $inquiries = Inquiry::whereIn('id', $request->inquiry_ids)->with('seller.user', 'product')->get();
        foreach ($inquiries as $inquiry) {
            if ($inquiry->seller->canReceiveNotifications()) {
                \App\Services\NotificationService::create(
                    $inquiry->seller->user->id,
                    'New Inquiry Assigned',
                    "An inquiry from {$inquiry->name} has been assigned to you.",
                    route('seller.inquiries.index')
                );
            }
        }

        return redirect()->back()->with('success', "{$updated} inquiries assigned successfully!");
    }

    public function export(Request $request)
    {
        $inquiries = Inquiry::with(['seller.user', 'buyer.user', 'product', 'assignedBy'])->get();

        $filename = 'inquiries_export_' . date('Y-m-d') . '.csv';
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => "attachment; filename=\"$filename\"",
        ];

        $callback = function() use ($inquiries) {
            $file = fopen('php://output', 'w');
            
            // Header row
            fputcsv($file, ['ID', 'Buyer Name', 'Buyer Email', 'Phone', 'Seller', 'Product', 'Message', 'Status', 'Admin Status', 'Assigned By', 'Date']);

            foreach ($inquiries as $inquiry) {
                fputcsv($file, [
                    $inquiry->id,
                    $inquiry->name,
                    $inquiry->email,
                    $inquiry->phone ?? 'N/A',
                    $inquiry->seller->company_name ?? 'N/A',
                    $inquiry->product->name ?? 'General Inquiry',
                    $inquiry->message,
                    ucfirst($inquiry->status),
                    ucfirst($inquiry->admin_status),
                    $inquiry->assignedBy->name ?? 'Not Assigned',
                    $inquiry->created_at->format('Y-m-d H:i'),
                ]);
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
