<?php
namespace Controllers\Admin;

use Core\Controller;
use Services\SmsService;

class SmsController extends Controller {

    public function index(): void {
        $this->requireRole('super-admin', 'admin');
        $sid  = $this->schoolId();
        $page = max(1, (int)$this->request->get('page', 1));

        $groups = [
            'all_parents'  => 'All Parents',
            'all_teachers' => 'All Teachers',
            'all_students' => 'All Students (own phones)',
            'class_1'      => 'Class 1 Parents',
            'class_2'      => 'Class 2 Parents',
            'class_3'      => 'Class 3 Parents',
            'class_4'      => 'Class 4 Parents',
            'class_5'      => 'Class 5 Parents',
            'class_6'      => 'Class 6 Parents',
            'unpaid_parents' => 'Parents with Unpaid Fees',
        ];

        $streams = $this->db->fetchAll(
            "SELECT st.id, CONCAT(cl.name,' ',st.name) AS full_name
             FROM streams st JOIN classes cl ON cl.id=st.class_id
             WHERE cl.school_id=? ORDER BY cl.level, st.name", [$sid]
        );
        $classes = $this->db->fetchAll("SELECT * FROM classes WHERE school_id=? ORDER BY level", [$sid]);

        $logs = $this->db->paginate(
            "SELECT nl.* FROM notifications_log nl
             WHERE nl.school_id=? AND nl.type='sms'
             ORDER BY nl.id DESC",
            [$sid], $page, 20
        );

        $this->view('admin/sms/index', compact('groups', 'streams', 'classes', 'logs'));
    }

    public function send(): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $sid     = $this->schoolId();
        $data    = $this->request->all();
        $message = trim($data['message'] ?? '');
        $type    = $data['recipient_type'] ?? 'group'; // group | individual

        if (!$message) { $this->withError('Message cannot be empty.'); $this->redirect('admin/sms'); return; }

        $sms   = new SmsService($sid);
        $phones = [];

        if ($type === 'individual') {
            $raw = trim($data['individual_phones'] ?? '');
            if (!$raw) { $this->withError('Enter at least one phone number.'); $this->redirect('admin/sms'); return; }
            foreach (preg_split('/[\s,;]+/', $raw) as $p) {
                $p = trim($p);
                if ($p) $phones[] = $sms->formatPhone($p);
            }
        } else {
            $group = $data['group'] ?? '';
            $phones = $this->resolveGroup($group, $sid, $data);
        }

        $phones = array_unique(array_filter($phones));
        if (empty($phones)) { $this->withError('No recipients found for the selected group.'); $this->redirect('admin/sms'); return; }

        $result = $sms->sendBulk($phones, $message, $sid);

        $this->withSuccess("SMS sent: {$result['sent']} delivered, {$result['failed']} failed out of " . count($phones) . " recipients.");
        $this->redirect('admin/sms');
    }

    private function resolveGroup(string $group, int $sid, array $data): array {
        $phones = [];

        if ($group === 'all_parents') {
            $rows = $this->db->fetchAll(
                "SELECT DISTINCT u.phone FROM parents p JOIN users u ON u.id=p.user_id
                 JOIN parent_student ps ON ps.parent_id=p.id
                 JOIN students s ON s.id=ps.student_id
                 WHERE s.school_id=? AND u.phone IS NOT NULL AND u.is_active=1", [$sid]
            );
        } elseif ($group === 'all_teachers') {
            $rows = $this->db->fetchAll(
                "SELECT u.phone FROM teachers t JOIN users u ON u.id=t.user_id
                 WHERE t.school_id=? AND u.phone IS NOT NULL AND u.is_active=1", [$sid]
            );
        } elseif ($group === 'all_students') {
            $rows = $this->db->fetchAll(
                "SELECT u.phone FROM students s JOIN users u ON u.id=s.user_id
                 WHERE s.school_id=? AND s.status='active' AND u.phone IS NOT NULL", [$sid]
            );
        } elseif ($group === 'unpaid_parents') {
            $rows = $this->db->fetchAll(
                "SELECT DISTINCT u.phone FROM parents p JOIN users u ON u.id=p.user_id
                 JOIN parent_student ps ON ps.parent_id=p.id
                 JOIN students s ON s.id=ps.student_id
                 JOIN fee_invoices fi ON fi.student_id=s.id
                 WHERE s.school_id=? AND fi.status != 'paid' AND u.phone IS NOT NULL AND u.is_active=1", [$sid]
            );
        } elseif (str_starts_with($group, 'class_')) {
            $level = (int)substr($group, 6);
            $rows  = $this->db->fetchAll(
                "SELECT DISTINCT u.phone FROM parents p JOIN users u ON u.id=p.user_id
                 JOIN parent_student ps ON ps.parent_id=p.id
                 JOIN students s ON s.id=ps.student_id
                 JOIN streams st ON st.id=s.stream_id
                 JOIN classes cl ON cl.id=st.class_id
                 WHERE s.school_id=? AND cl.level=? AND u.phone IS NOT NULL AND u.is_active=1", [$sid, $level]
            );
        } elseif ($group === 'stream') {
            $streamId = (int)($data['stream_id'] ?? 0);
            $rows = $this->db->fetchAll(
                "SELECT DISTINCT u.phone FROM parents p JOIN users u ON u.id=p.user_id
                 JOIN parent_student ps ON ps.parent_id=p.id
                 JOIN students s ON s.id=ps.student_id
                 WHERE s.school_id=? AND s.stream_id=? AND u.phone IS NOT NULL AND u.is_active=1", [$sid, $streamId]
            );
        } elseif ($group === 'custom_class') {
            $classId = (int)($data['class_id'] ?? 0);
            $rows = $this->db->fetchAll(
                "SELECT DISTINCT u.phone FROM parents p JOIN users u ON u.id=p.user_id
                 JOIN parent_student ps ON ps.parent_id=p.id
                 JOIN students s ON s.id=ps.student_id
                 JOIN streams st ON st.id=s.stream_id
                 WHERE s.school_id=? AND st.class_id=? AND u.phone IS NOT NULL AND u.is_active=1", [$sid, $classId]
            );
        } else {
            $rows = [];
        }

        foreach ($rows as $r) {
            if (!empty($r['phone'])) $phones[] = $r['phone'];
        }
        return $phones;
    }
}
