<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class MarketingController extends Controller
{
    public function index(Request $request)
    {
        $campaigns = \App\Models\MarketingCampaign::with('creator')
            ->when($request->search, fn ($q, $s) => $q->where('name', 'like', "%{$s}%"))
            ->when($request->status && $request->status !== 'all', fn ($q) => $q->where('status', request('status')))
            ->latest()->paginate(15);

        $stats = [
            'total' => \App\Models\MarketingCampaign::count(),
            'active' => \App\Models\MarketingCampaign::where('status', 'ACTIVE')->count(),
            'total_budget' => \App\Models\MarketingCampaign::sum('budget'),
        ];

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|string',
            'status' => 'required|string',
            'start_date' => 'required|date',
            'end_date' => 'nullable|date',
            'budget' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
        ]);
        \App\Models\MarketingCampaign::create(array_merge($validated, ['created_by' => auth()->id()]));

        return back()->with('success', 'Campaign created.');
    }

    // Sales module
    public function sales(Request $request)
    {
        $funnels = \App\Models\SalesFunnel::latest()->paginate(15);
        $targets = \App\Models\SalesTarget::with('assignee')->latest()->paginate(10);

        return view('admin.sales.index', compact('funnels', 'targets'));
    }

    // Feedback
    public function feedback(Request $request)
    {
        $feedbacks = \App\Models\CustomerFeedback::with('customer')
            ->when($request->status && $request->status !== 'all', fn ($q) => $q->where('status', request('status')))
            ->latest()->paginate(15);

        return view('admin.feedback.index', compact('feedbacks'));
    }

    // Customer Service
    public function customerService(Request $request)
    {
        $metrics = \App\Models\CustomerServiceMetric::latest('date')->paginate(15);
        $evaluations = \App\Models\ServiceEvaluation::with('customer')->latest()->take(10)->get();

        return view('admin.customer-service.index', compact('metrics', 'evaluations'));
    }
}
