#!/usr/bin/env php
<?php
/**
 * Send Follow-up Reminders
 * Cron job: Daily at 9 AM
 * Sends SMS/Email reminders for today's follow-ups
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

$pdo = getDB();
$logFile = __DIR__ . '/../logs/cron.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

logMessage("=== Starting reminder sending ===");

// Get today's follow-ups
$stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.follow_up_date,
                       u.full_name as doctor_name, u.email as doctor_email
                       FROM cases c
                       JOIN users u ON c.user_id = u.id
                       WHERE c.follow_up_date = CURDATE() 
                       AND c.status != 'closed'");
$stmt->execute();
$reminders = $stmt->fetchAll();

$smsSent = 0;
$emailSent = 0;

foreach ($reminders as $reminder) {
    $message = "Dear {$reminder['patient_name']}, this is a reminder from Dr. {$reminder['doctor_name']} ";
    $message .= "for your follow-up appointment today. Please contact the clinic if needed.";
    
    // Send SMS (implement your SMS gateway)
    // sendSMS($reminder['patient_mobile'], $message);
    
    // Send Email to patient (if email available)
    // mail($patientEmail, "Follow-up Reminder", $message);
    
    $smsSent++;
    
    // Log the reminder
    $stmt = $pdo->prepare("INSERT INTO reminder_logs (case_id, type, recipient, message, sent_at) 
                          VALUES (?, 'sms', ?, ?, NOW())");
    $stmt->execute([$reminder['id'], $reminder['patient_mobile'], $message]);
    
    logMessage("Reminder sent to {$reminder['patient_name']} ({$reminder['patient_mobile']})");
}

logMessage("Sent $smsSent SMS reminders");
logMessage("=== Reminder sending completed ===");