<?php
// cron/send_reminders.php
error_reporting(E_ALL);
ini_set('display_errors', 0);
require_once __DIR__ . '/../config.php';

set_time_limit(0);

$today = date('Y-m-d');
$intervals = [
    '1_day'  => date('Y-m-d', strtotime('+1 day')),
    '2_day'  => date('Y-m-d', strtotime('+2 days')),
    '3_day'  => date('Y-m-d', strtotime('+3 days')),
    '7_day'  => date('Y-m-d', strtotime('+7 days')),
];

$sent_count = 0;

foreach ($intervals as $type => $targetDate) {
    $sql = "SELECT a.id, a.patient_id, a.doctor_id, a.serial_no, a.appointment_date,
                   p.mobile AS patient_mobile, p.name AS patient_name,
                   d.name AS doctor_name, d.phone AS doctor_phone
            FROM opd_appointments a
            JOIN opd_patients p ON a.patient_id = p.id
            JOIN doctors d ON a.doctor_id = d.id
            WHERE a.status = 'confirmed' 
              AND a.appointment_date = '$targetDate'
              AND a.id NOT IN (
                  SELECT appointment_id FROM opd_reminders 
                  WHERE reminder_type = '$type' AND sent_to_patient = 1
              )";
    $result = $conn->query($sql);
    
    while ($row = $result->fetch_assoc()) {
        $dayText = ($type == '1_day') ? 'আগামীকাল' : str_replace('_', ' ', $type) . ' পর';
        $aptDate = date('d/m/Y', strtotime($row['appointment_date']));
        
        // Patient reminder
        $patientMsg = "প্রিয় {$row['patient_name']},\n{$dayText} আপনার OPD অ্যাপয়েন্টমেন্ট।\nডাক্তার: {$row['doctor_name']}\nতারিখ: {$aptDate}\nসিরিয়াল: #{$row['serial_no']}\nস্থানে উপস্থিত থাকার অনুরোধ রইল।";
        $sentPatient = sendSMS($row['patient_mobile'], $patientMsg);
        
        // Doctor reminder
        $doctorMsg = "অনুস্মারক: {$dayText} OPD অ্যাপয়েন্টমেন্ট।\nরোগী: {$row['patient_name']}\nসিরিয়াল: #{$row['serial_no']}\nতারিখ: {$aptDate}";
        $sentDoctor = sendSMS($row['doctor_phone'], $doctorMsg);
        
        // Log reminder
        $conn->query("INSERT INTO opd_reminders (appointment_id, reminder_type, sent_to_patient, sent_to_doctor) 
                      VALUES ({$row['id']}, '$type', " . ($sentPatient ? 1 : 0) . ", " . ($sentDoctor ? 1 : 0) . ")");
        $sent_count++;
    }
}

echo "Reminders sent: $sent_count";
?>