<?php

namespace App\Http\Controllers\SchoolAdmin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Student;
use App\Models\CommunicationLog;
use App\Services\AfricasTalkingService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class CommunicationController extends Controller
{
    protected $smsService;

    public function __construct(AfricasTalkingService $smsService)
    {
        $this->smsService = $smsService;
    }

    public function index()
    {
        $stats = [
            'total_sms' => CommunicationLog::where('type', 'SMS')->count(),
            'total_email' => CommunicationLog::where('type', 'Email')->count(),
            'failed_logs' => CommunicationLog::where('status', 'Failed')->count(),
        ];

        $recentLogs = CommunicationLog::latest()->take(10)->get();

        return view('schooladmin.communication.index', compact('stats', 'recentLogs'));
    }

    public function notifications()
    {
        $teachers = User::where('role', 'teacher')->get();
        $parents = User::where('role', 'parent')->get();
        $students = Student::with('parent')->get();

        return view('schooladmin.communication.notifications', compact('teachers', 'parents', 'students'));
    }

    public function send(Request $request)
    {
        $request->validate([
            'recipients' => 'required|array',
            'type' => 'required|in:SMS,Email,Both',
            'message' => 'required|string',
            'subject' => 'required_if:type,Email,Both|string|nullable',
        ]);

        $recipients = $request->recipients; // Array of IDs or Phone numbers depending on UI
        $type = $request->type;
        $messageContent = $request->message;
        $subject = $request->subject;

        $successCount = 0;
        $failCount = 0;

        foreach ($recipients as $recipientInfo) {
            // recipientInfo could be "user_123" or "student_456"
            list($role, $id) = explode('_', $recipientInfo);
            
            $contactEmail = null;
            $contactPhone = null;

            if ($role === 'user') {
                $user = User::find($id);
                if ($user) {
                    $contactEmail = $user->email;
                    $contactPhone = $user->phone;
                }
            } elseif ($role === 'student') {
                $student = Student::find($id);
                if ($student) {
                    $contactPhone = $student->parent_phone;
                    $contactEmail = $student->parent->email ?? null;
                }
            }

            if (!$contactEmail && !$contactPhone) continue;

            // Send SMS
            if ($type === 'SMS' || $type === 'Both') {
                if ($contactPhone) {
                    $result = $this->smsService.sendSms($contactPhone, $messageContent);
                    
                    CommunicationLog::create([
                        'school_id' => auth()->user()->school_id,
                        'recipient_contact' => $contactPhone,
                        'type' => 'SMS',
                        'content' => $messageContent,
                        'status' => $result['success'] ? 'Success' : 'Failed',
                        'error_message' => $result['success'] ? null : $result['message'],
                    ]);

                    $result['success'] ? $successCount++ : $failCount++;
                }
            }

            // Send Email
            if ($type === 'Email' || $type === 'Both') {
                if ($contactEmail) {
                    try {
                        Mail::raw($messageContent, function ($msg) use ($contactEmail, $subject) {
                            $msg->to($contactEmail)->subject($subject);
                        });

                        CommunicationLog::create([
                            'school_id' => auth()->user()->school_id,
                            'recipient_contact' => $contactEmail,
                            'type' => 'Email',
                            'subject' => $subject,
                            'content' => $messageContent,
                            'status' => 'Success',
                        ]);
                        $successCount++;
                    } catch (\Exception $e) {
                        Log::error('Email failed to ' . $contactEmail . ': ' . $e->getMessage());
                        CommunicationLog::create([
                            'school_id' => auth()->user()->school_id,
                            'recipient_contact' => $contactEmail,
                            'type' => 'Email',
                            'subject' => $subject,
                            'content' => $messageContent,
                            'status' => 'Failed',
                            'error_message' => $e->getMessage(),
                        ]);
                        $failCount++;
                    }
                }
            }
        }

        return redirect()->route('schooladmin.communication.index')
            ->with('success', "Messages sent: $successCount successes, $failCount failures.");
    }
}
