<?php

namespace App\Http\Controllers;

use App\Models\Communication;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class CommunicationController extends Controller
{
    /**
     * Display a listing of communications.
     */
    public function index()
    {
        $communications = Communication::with('creator')
            ->orderBy('created_at', 'desc')
            ->paginate(15);

        // Statistics
        $totalCommunications = Communication::count();
        $sentCommunications = Communication::where('status', 'sent')->count();
        $draftCommunications = Communication::where('status', 'draft')->count();
        $scheduledCommunications = Communication::where('status', 'scheduled')->count();

        return view('adminlte.communications.index', compact(
            'communications',
            'totalCommunications',
            'sentCommunications',
            'draftCommunications',
            'scheduledCommunications'
        ));
    }

    /**
     * Show the form for creating a new communication.
     */
    public function create()
    {
        $members = User::whereHas('roles', function ($query) {
            $query->where('name', 'Member');
        })->select('id', 'first_name', 'second_name', 'email')->get();

        return view('adminlte.communications.create', compact('members'));
    }

    /**
     * Store a newly created communication.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'content' => 'required|string',
            'recipient_type' => 'required|in:individual,all_members,specific_groups',
            'recipient_ids' => 'nullable|array',
            'recipient_ids.*' => 'exists:users,id',
            'priority' => 'required|in:low,normal,high,urgent',
            'send_now' => 'nullable|boolean',
            'scheduled_at' => 'nullable|date|after:now',
        ]);

        $communication = Communication::create([
            'subject' => $validated['subject'],
            'content' => $validated['content'],
            'recipient_type' => $validated['recipient_type'],
            'recipient_ids' => $validated['recipient_ids'] ?? null,
            'priority' => $validated['priority'],
            'status' => $request->input('send_now') ? 'sent' : 'draft',
            'scheduled_at' => $validated['scheduled_at'] ?? null,
            'created_by' => auth()->id(),
        ]);

        if ($request->input('send_now')) {
            $this->sendCommunication($communication);
        }

        return redirect()->route('communications.index')
            ->with('success', $request->input('send_now') ? 'Communication sent successfully!' : 'Communication saved as draft!');
    }

    /**
     * Display the specified communication.
     */
    public function show(Communication $communication)
    {
        $communication->load('creator');
        return view('adminlte.communications.show', compact('communication'));
    }

    /**
     * Show the form for editing the communication.
     */
    public function edit(Communication $communication)
    {
        if ($communication->status === 'sent') {
            return redirect()->route('communications.index')
                ->with('error', 'Cannot edit a sent communication.');
        }

        $members = User::whereHas('roles', function ($query) {
            $query->where('name', 'Member');
        })->select('id', 'first_name', 'second_name', 'email')->get();

        return view('adminlte.communications.edit', compact('communication', 'members'));
    }

    /**
     * Update the specified communication.
     */
    public function update(Request $request, Communication $communication)
    {
        if ($communication->status === 'sent') {
            return redirect()->route('communications.index')
                ->with('error', 'Cannot edit a sent communication.');
        }

        $validated = $request->validate([
            'subject' => 'required|string|max:255',
            'content' => 'required|string',
            'recipient_type' => 'required|in:individual,all_members,specific_groups',
            'recipient_ids' => 'nullable|array',
            'recipient_ids.*' => 'exists:users,id',
            'priority' => 'required|in:low,normal,high,urgent',
            'send_now' => 'nullable|boolean',
            'scheduled_at' => 'nullable|date|after:now',
        ]);

        $communication->update([
            'subject' => $validated['subject'],
            'content' => $validated['content'],
            'recipient_type' => $validated['recipient_type'],
            'recipient_ids' => $validated['recipient_ids'] ?? null,
            'priority' => $validated['priority'],
            'scheduled_at' => $validated['scheduled_at'] ?? null,
        ]);

        if ($request->input('send_now')) {
            $communication->update(['status' => 'sent']);
            $this->sendCommunication($communication);
        }

        return redirect()->route('communications.index')
            ->with('success', $request->input('send_now') ? 'Communication sent successfully!' : 'Communication updated successfully!');
    }

    /**
     * Send the communication to recipients.
     */
    public function send(Communication $communication)
    {
        if ($communication->status === 'sent') {
            return redirect()->route('communications.index')
                ->with('error', 'Communication has already been sent.');
        }

        $this->sendCommunication($communication);

        return redirect()->route('communications.index')
            ->with('success', 'Communication sent successfully!');
    }

    /**
     * Remove the specified communication.
     */
    public function destroy(Communication $communication)
    {
        if ($communication->status === 'sent') {
            return redirect()->route('communications.index')
                ->with('error', 'Cannot delete a sent communication.');
        }

        $communication->delete();

        return redirect()->route('communications.index')
            ->with('success', 'Communication deleted successfully!');
    }

    /**
     * Send communication to recipients
     */
    private function sendCommunication(Communication $communication)
    {
        $recipients = $communication->getRecipients();

        foreach ($recipients as $recipient) {
            try {
                Mail::raw($communication->content, function ($message) use ($communication, $recipient) {
                    $message->to($recipient->email)
                            ->subject($communication->subject)
                            ->from(config('mail.from.address'), config('mail.from.name'));
                });

                Log::info("Email sent to {$recipient->email} for communication ID: {$communication->id}");
            } catch (\Exception $e) {
                Log::error("Failed to send email to {$recipient->email}: " . $e->getMessage());
            }
        }

        $communication->update([
            'status' => 'sent',
            'sent_at' => now(),
        ]);
    }
}
