<?php

/**

 * Timetable lesson reminder cron — emails teachers 15 minutes before their lesson.

 *

 * Run every 5 minutes via cPanel cron:

 *   *\/5 * * * *  curl -s "https://https://edutrack.oricnetwork.com/timetable_notify_cron.php?token=072b727e0e2dda798f595a090e98c5eeaaad33003d35871e4df90c1f62188104" > /dev/null

 *

 * Token: set TIMETABLE_CRON_TOKEN in your .env or config.php, or hardcode below.

 *

 * The query window is 13–17 minutes before lesson start, so any cron fire

 * within that 4-minute band catches the notification exactly once.

 */



declare(strict_types=1);

require_once __DIR__ . '/config.php';



// ── Token protection ──────────────────────────────────────────────────────────

$token = trim($_GET['token'] ?? $_SERVER['argv'][1] ?? '');



// Allow defining TIMETABLE_CRON_TOKEN in config.php/.env, or fall back to a

// value stored in the settings table. If none configured, block all web requests.

$expected = '';

if (defined('TIMETABLE_CRON_TOKEN')) {

    $expected = TIMETABLE_CRON_TOKEN;

} else {

    $expected = (string) (getSettingValue('timetable_cron_token') ?? '');

}



$is_cli = (php_sapi_name() === 'cli');

if (!$is_cli) {

    if ($expected === '' || !hash_equals($expected, $token)) {

        http_response_code(403);

        exit('Forbidden.');

    }

}



// ── Ensure reminder_type enum includes 15_min ─────────────────────────────────

$conn = getDBConnection();

$conn->query(

    "ALTER TABLE timetable_email_reminders

     MODIFY COLUMN reminder_type ENUM('30_min','15_min','10_min') NOT NULL DEFAULT '15_min'"

);



// ── Read current academic year + term from settings ────────────────────────────

$academic_year = (string) (getSettingValue('academic_year') ?? date('Y'));

$current_term  = (string) (getSettingValue('current_term')  ?? '');



// ── Find lessons starting in 13–17 minutes that haven't been notified yet ─────

// day_of_week ENUM: 'Mon','Tue','Wed','Thu','Fri','Sat'

// MySQL DATE_FORMAT(NOW(), '%a') → 'Tue', 'Wed', etc.

// TIME(NOW()) + 13–17 minutes brackets the 15-minute target.



$sql = "

    SELECT

        ts.id           AS slot_id,

        ts.class_name,

        ts.day_of_week,

        tp.period_name,

        tp.start_time,

        tp.end_time,

        ts.teacher_id,

        u.full_name     AS teacher_name,

        u.email         AS teacher_email,

        COALESCE(s.subject_name, ts.class_name) AS subject_name

    FROM timetable_slots ts

    JOIN timetable_periods tp ON tp.id = ts.period_id

    JOIN users u              ON u.id  = ts.teacher_id

                             AND u.email != ''

                             AND u.is_active = 1

    LEFT JOIN subjects s      ON s.id  = ts.subject_id

    WHERE ts.day_of_week   = DATE_FORMAT(NOW(), '%a')

      AND tp.is_break      = 0

      AND ts.teacher_id    IS NOT NULL

      AND ts.academic_year = ?

      AND TIME(NOW()) BETWEEN SUBTIME(tp.start_time, '00:17:00')

                          AND SUBTIME(tp.start_time, '00:13:00')

      AND NOT EXISTS (

          SELECT 1 FROM timetable_email_reminders ter

          WHERE ter.teacher_id    = ts.teacher_id

            AND ter.slot_id       = ts.id

            AND ter.schedule_date = CURDATE()

            AND ter.reminder_type = '15_min'

      )

";



$params = [$academic_year];

if ($current_term !== '') {

    $sql     .= " AND ts.term = ?";

    $params[] = $current_term;

}



$stmt = $conn->prepare($sql);

if (!$stmt) {

    error_log('timetable_notify_cron prepare failed: ' . $conn->error);

    exit(1);

}



// Bind params dynamically

$types = str_repeat('s', count($params));

$stmt->bind_param($types, ...$params);

$stmt->execute();

$slots = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stmt->close();



if (empty($slots)) {

    if ($is_cli) echo '[' . date('H:i:s') . '] No lessons due for 15-minute reminder.' . PHP_EOL;

    exit(0);

}



// ── Build email body ───────────────────────────────────────────────────────────

$school_name = (string) (getSettingValue('school_name') ?? 'School');



$sent   = 0;

$failed = 0;



foreach ($slots as $slot) {

    $teacher_email = $slot['teacher_email'];

    $teacher_name  = $slot['teacher_name'];

    $subject_name  = $slot['subject_name'];

    $class_name    = $slot['class_name'];

    $period_name   = $slot['period_name'];

    $start_time    = date('h:i A', strtotime($slot['start_time']));

    $end_time      = date('h:i A', strtotime($slot['end_time']));

    $slot_id       = (int) $slot['slot_id'];

    $teacher_id    = (int) $slot['teacher_id'];



    $subject = "{$school_name} — Lesson Reminder: {$subject_name} starts in 15 minutes";



    $body = <<<HTML

<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <style>

    body { font-family: Arial, sans-serif; background: #f4f4f4; margin: 0; padding: 0; }

    .wrap { max-width: 560px; margin: 30px auto; background: #fff; border-radius: 10px; overflow: hidden; }

    .header { background: #1e3a5f; color: #fff; padding: 24px 28px; }

    .header h2 { margin: 0; font-size: 1.2rem; }

    .body { padding: 28px; color: #333; line-height: 1.6; }

    .lesson-card {

      background: #f0f7ff; border-left: 4px solid #2563eb;

      border-radius: 8px; padding: 16px 20px; margin: 16px 0;

    }

    .lesson-card .subject { font-size: 1.3rem; font-weight: 700; color: #1e3a5f; }

    .lesson-card .meta    { color: #555; margin-top: 4px; font-size: .9rem; }

    .time-badge { display: inline-block; background: #2563eb; color: #fff; padding: 4px 12px; border-radius: 20px; font-size: .85rem; font-weight: 600; margin-top: 8px; }

    .footer { background: #f4f4f4; padding: 16px 28px; font-size: .75rem; color: #888; }

  </style>

</head>

<body>

  <div class="wrap">

    <div class="header">

      <h2>⏰ Lesson Reminder — {$school_name}</h2>

    </div>

    <div class="body">

      <p>Dear <strong>{$teacher_name}</strong>,</p>

      <p>This is a reminder that your lesson begins in approximately <strong>15 minutes</strong>.</p>

      <div class="lesson-card">

        <div class="subject">{$subject_name}</div>

        <div class="meta">Class: <strong>{$class_name}</strong></div>

        <div class="meta">Period: {$period_name}</div>

        <div class="time-badge">🕐 {$start_time} – {$end_time}</div>

      </div>

      <p>Please ensure you are prepared and heading to the classroom on time. Thank you!</p>

    </div>

    <div class="footer">

      {$school_name} · EduTrack School Management · Automated reminder — do not reply.

    </div>

  </div>

</body>

</html>

HTML;



    $ok = sendEmail($teacher_email, $subject, $body);



    // Log to timetable_email_reminders

    $log_stmt = $conn->prepare(

        "INSERT INTO timetable_email_reminders

           (teacher_id, slot_id, schedule_date, reminder_type, recipient_email, status, sent_at)

         VALUES (?, ?, CURDATE(), '15_min', ?, ?, NOW())"

    );

    $status = $ok ? 'sent' : 'failed';

    $log_stmt->bind_param('iiss', $teacher_id, $slot_id, $teacher_email, $status);

    $log_stmt->execute();

    $log_stmt->close();



    if ($ok) {

        $sent++;

        if ($is_cli) echo "[{$start_time}] Sent → {$teacher_name} ({$teacher_email}) — {$subject_name} / {$class_name}" . PHP_EOL;

    } else {

        $failed++;

        error_log("timetable_notify_cron: failed to email {$teacher_email} for slot {$slot_id}");

    }

}



$conn->close();



if ($is_cli) {

    echo '[' . date('H:i:s') . "] Done. Sent: {$sent}, Failed: {$failed}" . PHP_EOL;

}

