<?php
namespace Controllers\Admin;

use Core\Controller;
use Models\Attendance;
use Models\Student;
use Models\Stream;
use Services\SmsService;

class AttendanceController extends Controller {
    public function index(): void {
        $this->requireRole('super-admin', 'admin');
        $date    = $this->request->get('date', date('Y-m-d'));
        $streams = (new Stream())->getBySchool($this->schoolId());
        $summary = (new Attendance())->getSummary($this->schoolId(), $date);
        $this->view('admin/attendance/index', compact('streams', 'date', 'summary'));
    }

    public function take(string $streamId): void {
        $this->requireRole('super-admin', 'admin');
        $date     = $this->request->get('date', date('Y-m-d'));
        $stream   = (new Stream())->getWithClass((int)$streamId);
        $students = (new Student())->getByStream((int)$streamId);
        $existing = [];
        foreach ($students as $s) {
            $rec = (new Attendance())->getByStudentDate($s['id'], $date);
            $existing[$s['id']] = $rec['status'] ?? 'present';
        }
        $this->view('admin/attendance/take', compact('stream', 'students', 'date', 'existing'));
    }

    public function save(string $streamId): void {
        $this->requireRole('super-admin', 'admin');
        $this->verifyCsrf();
        $date       = $this->request->post('date', date('Y-m-d'));
        $attendance = $this->request->post('attendance', []);
        $model      = new Attendance();
        $sms        = new SmsService();
        $absentees  = [];

        foreach ($attendance as $studentId => $status) {
            $model->upsert((int)$studentId, (int)$streamId, $date, $status, $this->currentUser()['id']);
            if ($status === 'absent') {
                $parents = $this->db->fetchAll(
                    "SELECT u.phone, u.name AS parent_name, su.name AS student_name
                     FROM parent_student ps
                     JOIN parents p ON p.id=ps.parent_id
                     JOIN users u ON u.id=p.user_id
                     JOIN students s ON s.id=ps.student_id
                     JOIN users su ON su.id=s.user_id
                     WHERE ps.student_id=?", [(int)$studentId]
                );
                foreach ($parents as $parent) {
                    if ($parent['phone']) {
                        $absentees[] = ['phone'=>$parent['phone'],'student'=>$parent['student_name']];
                    }
                }
            }
        }
        $smsSent = 0;
        foreach ($absentees as $info) {
            $msg = "Dear Parent, {$info['student']} was absent from school on " . date('d/m/Y', strtotime($date)) . ". Please contact the school.";
            if ($sms->send($info['phone'], $msg, $this->schoolId())) $smsSent++;
        }
        $this->withSuccess('Attendance saved. ' . $smsSent . ' SMS alerts sent.');
        $this->redirect('admin/attendance');
    }

    public function report(): void {
        $this->requireRole('super-admin', 'admin');
        $from = $this->request->get('from', date('Y-m-01'));
        $to   = $this->request->get('to', date('Y-m-d'));
        $data = $this->db->fetchAll(
            "SELECT a.student_id, a.status, COUNT(*) as cnt,
                    u.name AS student_name, s.assessment_no,
                    cl.name AS class_name, st.name AS stream_name
             FROM attendances a
             JOIN students s ON s.id=a.student_id
             JOIN users u ON u.id=s.user_id
             LEFT JOIN streams st ON st.id=s.stream_id
             LEFT JOIN classes cl ON cl.id=st.class_id
             WHERE s.school_id=? AND a.date BETWEEN ? AND ?
             GROUP BY a.student_id, a.status
             ORDER BY u.name",
            [$this->schoolId(), $from, $to]
        );
        $grouped = [];
        foreach ($data as $row) {
            $sid = $row['student_id'];
            if (!isset($grouped[$sid])) {
                $grouped[$sid] = ['name'=>$row['student_name'],'assessment_no'=>$row['assessment_no'],
                    'class'=>$row['class_name'],'stream'=>$row['stream_name'],
                    'present'=>0,'absent'=>0,'late'=>0,'excused'=>0];
            }
            $grouped[$sid][$row['status']] = (int)$row['cnt'];
        }
        $this->view('admin/attendance/report', compact('grouped', 'from', 'to'));
    }
}

