<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Models\Student;
use App\Models\Teacher;
use App\Models\ParentModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class CommunicationController extends ApiController
{
    /**
     * Send SMS to selected recipients
     */
    public function sendSms(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'recipient_type' => 'required|in:students,teachers,parents,staff,custom',
            'message' => 'required|string|max:1000',
            'recipient_ids' => 'nullable|array',
            'recipient_ids.*' => 'integer',
            'class_id' => 'nullable|exists:school_classes,id',
            'section_id' => 'nullable|exists:sections,id',
            'phone_numbers' => 'nullable|array',
            'phone_numbers.*' => 'string',
            'schedule_date' => 'nullable|date|after_or_equal:now',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        try {
            $phoneNumbers = [];
            $recipientType = $request->recipient_type;

            // Get phone numbers based on recipient type
            switch ($recipientType) {
                case 'students':
                    $query = Student::query();

                    if ($request->has('recipient_ids') && !empty($request->recipient_ids)) {
                        $query->whereIn('id', $request->recipient_ids);
                    }

                    if ($request->has('class_id') && $request->class_id) {
                        $query->where('class_id', $request->class_id);
                    }

                    if ($request->has('section_id') && $request->section_id) {
                        $query->where('section_id', $request->section_id);
                    }

                    $phoneNumbers = $query->whereNotNull('phone')
                        ->pluck('phone')
                        ->filter()
                        ->unique()
                        ->values()
                        ->toArray();
                    break;

                case 'teachers':
                    $query = Teacher::query();

                    if ($request->has('recipient_ids') && !empty($request->recipient_ids)) {
                        $query->whereIn('id', $request->recipient_ids);
                    }

                    $phoneNumbers = $query->whereNotNull('phone')
                        ->pluck('phone')
                        ->filter()
                        ->unique()
                        ->values()
                        ->toArray();
                    break;

                case 'parents':
                    $query = Student::query();

                    if ($request->has('class_id') && $request->class_id) {
                        $query->where('class_id', $request->class_id);
                    }

                    $students = $query->whereNotNull('father_phone')->orWhereNotNull('mother_phone')->get();

                    foreach ($students as $student) {
                        if ($student->father_phone) {
                            $phoneNumbers[] = $student->father_phone;
                        }
                        if ($student->mother_phone) {
                            $phoneNumbers[] = $student->mother_phone;
                        }
                    }

                    $phoneNumbers = array_unique(array_filter($phoneNumbers));
                    break;

                case 'custom':
                    if (!$request->has('phone_numbers') || empty($request->phone_numbers)) {
                        return $this->errorResponse('Phone numbers are required for custom recipients', 422);
                    }
                    $phoneNumbers = $request->phone_numbers;
                    break;
            }

            if (empty($phoneNumbers)) {
                return $this->errorResponse('No valid phone numbers found for the selected recipients', 400);
            }

            // Here you would integrate with an SMS service provider (Twilio, AWS SNS, etc.)
            // For now, we'll log the SMS details
            $smsData = [
                'recipient_type' => $recipientType,
                'message' => $request->message,
                'phone_numbers' => $phoneNumbers,
                'total_recipients' => count($phoneNumbers),
                'sent_by' => auth('admin')->id(),
                'schedule_date' => $request->schedule_date,
                'status' => $request->schedule_date ? 'scheduled' : 'sent',
            ];

            Log::info('SMS Send Request', $smsData);

            // TODO: Implement actual SMS sending logic
            // Example: Twilio integration
            // $twilio = new \Twilio\Rest\Client($sid, $token);
            // foreach ($phoneNumbers as $number) {
            //     $twilio->messages->create($number, ['from' => $from, 'body' => $message]);
            // }

            // Store in database (create sms_logs table)
            // SmsLog::create($smsData);

            return $this->successResponse([
                'total_recipients' => count($phoneNumbers),
                'status' => $smsData['status'],
                'message' => $request->schedule_date
                    ? 'SMS scheduled successfully'
                    : 'SMS sent successfully (simulation)',
                'recipients' => $phoneNumbers,
            ], 'SMS processed successfully');

        } catch (\Exception $e) {
            Log::error('SMS Send Error', ['error' => $e->getMessage()]);
            return $this->errorResponse('Failed to send SMS: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Send Email to selected recipients
     */
    public function sendEmail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'recipient_type' => 'required|in:students,teachers,parents,staff,custom',
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
            'recipient_ids' => 'nullable|array',
            'recipient_ids.*' => 'integer',
            'class_id' => 'nullable|exists:school_classes,id',
            'section_id' => 'nullable|exists:sections,id',
            'email_addresses' => 'nullable|array',
            'email_addresses.*' => 'email',
            'attachments' => 'nullable|array',
            'attachments.*' => 'string',
            'schedule_date' => 'nullable|date|after_or_equal:now',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        try {
            $emailAddresses = [];
            $recipientType = $request->recipient_type;

            // Get email addresses based on recipient type
            switch ($recipientType) {
                case 'students':
                    $query = Student::query();

                    if ($request->has('recipient_ids') && !empty($request->recipient_ids)) {
                        $query->whereIn('id', $request->recipient_ids);
                    }

                    if ($request->has('class_id') && $request->class_id) {
                        $query->where('class_id', $request->class_id);
                    }

                    if ($request->has('section_id') && $request->section_id) {
                        $query->where('section_id', $request->section_id);
                    }

                    $emailAddresses = $query->whereNotNull('email')
                        ->pluck('email')
                        ->filter()
                        ->unique()
                        ->values()
                        ->toArray();
                    break;

                case 'teachers':
                    $query = Teacher::query();

                    if ($request->has('recipient_ids') && !empty($request->recipient_ids)) {
                        $query->whereIn('id', $request->recipient_ids);
                    }

                    $emailAddresses = $query->whereNotNull('email')
                        ->pluck('email')
                        ->filter()
                        ->unique()
                        ->values()
                        ->toArray();
                    break;

                case 'parents':
                    $query = Student::query();

                    if ($request->has('class_id') && $request->class_id) {
                        $query->where('class_id', $request->class_id);
                    }

                    $students = $query->whereNotNull('father_email')->orWhereNotNull('mother_email')->get();

                    foreach ($students as $student) {
                        if ($student->father_email) {
                            $emailAddresses[] = $student->father_email;
                        }
                        if ($student->mother_email) {
                            $emailAddresses[] = $student->mother_email;
                        }
                    }

                    $emailAddresses = array_unique(array_filter($emailAddresses));
                    break;

                case 'custom':
                    if (!$request->has('email_addresses') || empty($request->email_addresses)) {
                        return $this->errorResponse('Email addresses are required for custom recipients', 422);
                    }
                    $emailAddresses = $request->email_addresses;
                    break;
            }

            if (empty($emailAddresses)) {
                return $this->errorResponse('No valid email addresses found for the selected recipients', 400);
            }

            // Here you would integrate with an email service (Laravel Mail, SendGrid, AWS SES, etc.)
            $emailData = [
                'recipient_type' => $recipientType,
                'subject' => $request->subject,
                'message' => $request->message,
                'email_addresses' => $emailAddresses,
                'total_recipients' => count($emailAddresses),
                'attachments' => $request->attachments ?? [],
                'sent_by' => auth('admin')->id(),
                'schedule_date' => $request->schedule_date,
                'status' => $request->schedule_date ? 'scheduled' : 'sent',
            ];

            Log::info('Email Send Request', $emailData);

            // TODO: Implement actual email sending logic
            // Example: Laravel Mail
            // Mail::to($emailAddresses)->send(new SchoolNotification($emailData));

            // Store in database (create email_logs table)
            // EmailLog::create($emailData);

            return $this->successResponse([
                'total_recipients' => count($emailAddresses),
                'status' => $emailData['status'],
                'message' => $request->schedule_date
                    ? 'Email scheduled successfully'
                    : 'Email sent successfully (simulation)',
                'recipients' => $emailAddresses,
            ], 'Email processed successfully');

        } catch (\Exception $e) {
            Log::error('Email Send Error', ['error' => $e->getMessage()]);
            return $this->errorResponse('Failed to send email: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get communication history/logs
     */
    public function history(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $type = $request->get('type', 'all'); // all, sms, email

        // TODO: Implement when sms_logs and email_logs tables are created
        // For now, return a placeholder response

        return $this->successResponse([
            'message' => 'Communication history will be available once logging tables are created',
            'type' => $type,
        ]);
    }
}
