<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\CommunicationLog;
use App\Models\CommunicationTemplate;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CommunicationCenterController extends Controller
{
    public function index(Request $request)
    {
        $logs = CommunicationLog::with(['customer', 'application', 'user'])
            ->when($request->filled('channel'), fn ($q) => $q->where('channel', $request->string('channel')))
            ->when($request->filled('status'), fn ($q) => $q->where('status', $request->string('status')))
            ->latest()->paginate(20)->withQueryString();
        $templates = CommunicationTemplate::orderBy('channel')->orderBy('name_en')->get();
        $channelCounts = CommunicationLog::selectRaw('channel, COUNT(*) as total')->groupBy('channel')->pluck('total', 'channel');
        $failedCount = CommunicationLog::where('status', 'failed')->count();
        $customers = Customer::with('contact')->where('status', 'active')->orderBy('full_name_en')->limit(100)->get();

        return view('tenant.operations.communication', compact('logs', 'templates', 'channelCounts', 'failedCount', 'customers'));
    }

    public function storeTemplate(Request $request)
    {
        $validated = $request->validate([
            'channel' => ['required', Rule::in(['whatsapp', 'sms', 'email'])],
            'template_code' => ['required', 'alpha_dash', 'max:80'],
            'name_en' => ['required', 'string', 'max:120'],
            'content_en' => ['required', 'string', 'max:5000'],
            'content_ar' => ['nullable', 'string', 'max:5000'],
        ]);

        $template = CommunicationTemplate::updateOrCreate(
            ['tenant_id' => auth()->user()->tenant_id, 'channel' => $validated['channel'], 'template_code' => $validated['template_code']],
            $validated + ['is_active' => true]
        );
        AuditLog::record('communications', 'template.saved', $template);

        return back()->with('status', 'Communication template saved.');
    }

    public function queueMessage(Request $request)
    {
        $tenantId = auth()->user()->tenant_id;
        $validated = $request->validate([
            'channel' => ['required', Rule::in(['whatsapp', 'sms', 'email'])],
            'recipient' => ['required', 'string', 'max:180'],
            'subject' => ['nullable', 'string', 'max:180'],
            'message' => ['required', 'string', 'max:5000'],
            'template_code' => ['nullable', 'string', 'max:80'],
            'customer_id' => ['nullable', Rule::exists('customers', 'id')->where('tenant_id', $tenantId)],
            'application_id' => ['nullable', Rule::exists('applications', 'id')->where('tenant_id', $tenantId)],
        ]);

        $log = CommunicationLog::create($validated + [
            'direction' => 'outbound',
            'summary' => str($validated['message'])->limit(180),
            'status' => 'queued',
            'user_id' => auth()->id(),
        ]);
        AuditLog::record('communications', 'message.queued', $log);

        return back()->with('status', ucfirst($log->channel).' message queued. Connect a provider in Communication Settings to deliver it.');
    }
}
