<?php

namespace App\Http\Controllers;

use App\Models\Mailing;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;

class MailingsController extends Controller
{
    /**
     * Display the mailings management page
     */
    public function index()
    {
        // Check authorization - only admins and banks can manage mailings
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to access mailings management.');
        }

        return view('mailings.manage');
    }

    /**
     * Store a new mailing
     */
    public function store(Request $request)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to create mailings.');
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'type' => ['required', Rule::in(['local_newsletter', 'general_newsletter', 'system_message'])],
            'subject' => 'required|string|max:255',
            'content_blocks' => 'nullable|array',
            'content_blocks.*.post_id' => 'required|integer|exists:posts,id',
            'content_blocks.*.order' => 'required|integer|min:1',
            'scheduled_at' => 'nullable|date|after:now',
        ]);

        // Determine creator
        $creator = Auth::guard('admin')->user() ?: Auth::guard('bank')->user();

        $mailing = Mailing::create([
            'title' => $validated['title'],
            'type' => $validated['type'],
            'subject' => $validated['subject'],
            'content_blocks' => $validated['content_blocks'] ?? [],
            'scheduled_at' => $validated['scheduled_at'] ?? null,
            'status' => $validated['scheduled_at'] ? 'scheduled' : 'draft',
            'created_by_id' => $creator->id,
            'created_by_type' => get_class($creator),
        ]);

        // Update recipient count
        $mailing->recipients_count = $mailing->getRecipientsQuery()->count();
        $mailing->save();

        return response()->json([
            'success' => true,
            'message' => 'Mailing created successfully.',
            'mailing' => $mailing->load('createdBy')
        ]);
    }

    /**
     * Update an existing mailing
     */
    public function update(Request $request, Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to update mailings.');
        }

        // Can only edit drafts
        if (!$mailing->canBeScheduled()) {
            return response()->json(['error' => 'Only draft mailings can be edited.'], 422);
        }

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'type' => ['required', Rule::in(['local_newsletter', 'general_newsletter', 'system_message'])],
            'subject' => 'required|string|max:255',
            'content_blocks' => 'nullable|array',
            'content_blocks.*.post_id' => 'required|integer|exists:posts,id',
            'content_blocks.*.order' => 'required|integer|min:1',
            'scheduled_at' => 'nullable|date|after:now',
        ]);

        $mailing->update([
            'title' => $validated['title'],
            'type' => $validated['type'],
            'subject' => $validated['subject'],
            'content_blocks' => $validated['content_blocks'] ?? [],
            'scheduled_at' => $validated['scheduled_at'] ?? null,
            'status' => $validated['scheduled_at'] ? 'scheduled' : 'draft',
        ]);

        // Update recipient count
        $mailing->recipients_count = $mailing->getRecipientsQuery()->count();
        $mailing->save();

        return response()->json([
            'success' => true,
            'message' => 'Mailing updated successfully.',
            'mailing' => $mailing->load('createdBy')
        ]);
    }

    /**
     * Delete a mailing (soft delete)
     */
    public function destroy(Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to delete mailings.');
        }

        // Can only delete drafts and scheduled mailings
        if (!in_array($mailing->status, ['draft', 'scheduled'])) {
            return response()->json(['error' => 'Cannot delete sent or sending mailings.'], 422);
        }

        $mailing->delete();

        return response()->json([
            'success' => true,
            'message' => 'Mailing deleted successfully.'
        ]);
    }

    /**
     * Send a mailing immediately
     */
    public function send(Request $request, Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to send mailings.');
        }

        if (!$mailing->canBeSent()) {
            return response()->json(['error' => 'Mailing cannot be sent in its current status.'], 422);
        }

        // Update status to sending
        $mailing->update(['status' => 'sending']);

        // Dispatch bulk email job (to be implemented in Phase 6)
        // SendBulkMailJob::dispatch($mailing);

        return response()->json([
            'success' => true,
            'message' => 'Mailing is being sent. This process may take several minutes.',
            'mailing' => $mailing
        ]);
    }

    /**
     * Schedule a mailing for future sending
     */
    public function schedule(Request $request, Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to schedule mailings.');
        }

        if (!$mailing->canBeScheduled()) {
            return response()->json(['error' => 'Mailing cannot be scheduled in its current status.'], 422);
        }

        $validated = $request->validate([
            'scheduled_at' => 'required|date|after:now',
        ]);

        $mailing->update([
            'scheduled_at' => $validated['scheduled_at'],
            'status' => 'scheduled'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Mailing scheduled successfully.',
            'mailing' => $mailing
        ]);
    }

    /**
     * Cancel a scheduled mailing
     */
    public function cancel(Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to cancel mailings.');
        }

        if (!$mailing->canBeCancelled()) {
            return response()->json(['error' => 'Mailing cannot be cancelled in its current status.'], 422);
        }

        $mailing->update([
            'scheduled_at' => null,
            'status' => 'draft'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Scheduled mailing cancelled and reverted to draft.',
            'mailing' => $mailing
        ]);
    }

    /**
     * Preview a mailing
     */
    public function preview(Request $request, Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to preview mailings.');
        }

        // Get current user as preview recipient
        $recipient = Auth::guard('admin')->user() ?: Auth::guard('bank')->user();

        // Generate preview using NewsletterMail
        $newsletterMail = new \App\Mail\NewsletterMail($mailing, $recipient);

        return response()->json([
            'success' => true,
            'preview_url' => route('mailings.preview_render', $mailing->id)
        ]);
    }

    /**
     * Render mailing preview as HTML
     */
    public function previewRender(Mailing $mailing)
    {
        // Authorization check
        if (!Auth::guard('admin')->check() && !Auth::guard('bank')->check()) {
            abort(403, 'Unauthorized to preview mailings.');
        }

        // Get current user as preview recipient
        $recipient = Auth::guard('admin')->user() ?: Auth::guard('bank')->user();

        // Generate and render preview
        $newsletterMail = new \App\Mail\NewsletterMail($mailing, $recipient);

        return $newsletterMail->render();
    }
}