<?php
// api/send_appointment_reminder.php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['appointment_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing appointment ID']);
    exit();
}

$appointment_id = (int)$input['appointment_id'];
$user_id = $_SESSION['user_id'];

// Fetch appointment details
$sql = "SELECT 
            a.*,
            p.patient_number,
            pu.full_name as patient_name,
            pu.phone_primary as patient_phone,
            pu.email as patient_email,
            d.full_name as doctor_name
        FROM appointments a
        INNER JOIN patients p ON a.patient_id = p.patient_id
        INNER JOIN users pu ON p.user_id = pu.user_id
        INNER JOIN users d ON a.doctor_id = d.user_id
        WHERE a.appointment_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $appointment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Appointment not found']);
    exit();
}

$appointment = $result->fetch_assoc();

// Fetch SMS and Email settings
$settings_sql = "SELECT setting_key, setting_value FROM system_settings 
                WHERE category IN ('sms', 'email', 'video_conferencing')";
$settings_result = $conn->query($settings_sql);
$settings = [];
while ($row = $settings_result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$sms_sent = false;
$email_sent = false;
$messages = [];

// Prepare appointment details
$appointment_date = date('l, F j, Y', strtotime($appointment['appointment_date']));
$appointment_time = date('h:i A', strtotime($appointment['appointment_time']));

// Send SMS if enabled
if (($settings['sms_enabled'] ?? '0') == '1' && !empty($appointment['patient_phone'])) {
    require_once '../includes/africastalking.php'; // Your Africa's Talking integration file
    
    $message = "Hello {$appointment['patient_name']}, \n\n";
    $message .= "This is a reminder for your TELEMEDICINE appointment:\n";
    $message .= "Date: {$appointment_date}\n";
    $message .= "Time: {$appointment_time}\n";
    $message .= "Doctor: {$appointment['doctor_name']}\n";
    $message .= "Appointment #: {$appointment['appointment_number']}\n\n";
    $message .= "Please be ready with a stable internet connection.\n";
    $message .= "Thank you!";
    
    try {
        // Send SMS using Africa's Talking
        $sms_result = sendSMS($appointment['patient_phone'], $message);
        if ($sms_result['success']) {
            $sms_sent = true;
            $messages[] = 'SMS sent successfully';
        } else {
            $messages[] = 'SMS failed: ' . $sms_result['message'];
        }
    } catch (Exception $e) {
        $messages[] = 'SMS error: ' . $e->getMessage();
    }
}

// Send Email if enabled
if (($settings['email_enabled'] ?? '0') == '1' && !empty($appointment['patient_email'])) {
    require_once '../includes/phpmailer_config.php'; // Your PHPMailer configuration
    
    $subject = "Reminder: Your Telemedicine Appointment - {$appointment['appointment_number']}";
    
    $email_body = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: linear-gradient(135deg, #06b6d4, #0891b2); color: white; padding: 20px; border-radius: 8px; }
            .content { background: #f9fafb; padding: 20px; border-radius: 8px; margin-top: 20px; }
            .details { background: white; padding: 15px; border-left: 4px solid #06b6d4; margin: 15px 0; }
            .footer { text-align: center; margin-top: 20px; color: #6b7280; font-size: 0.875rem; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>🎥 Telemedicine Appointment Reminder</h2>
            </div>
            <div class='content'>
                <p>Dear {$appointment['patient_name']},</p>
                <p>This is a friendly reminder about your upcoming telemedicine consultation:</p>
                
                <div class='details'>
                    <p><strong>Appointment Number:</strong> {$appointment['appointment_number']}</p>
                    <p><strong>Date:</strong> {$appointment_date}</p>
                    <p><strong>Time:</strong> {$appointment_time}</p>
                    <p><strong>Doctor:</strong> {$appointment['doctor_name']}</p>
                    <p><strong>Type:</strong> Telemedicine (Video Consultation)</p>
                </div>
                
                <h3>📋 Before Your Appointment:</h3>
                <ul>
                    <li>Ensure you have a stable internet connection</li>
                    <li>Test your camera and microphone</li>
                    <li>Find a quiet, well-lit space</li>
                    <li>Have your medical history and current medications ready</li>
                    <li>Write down any questions or concerns</li>
                </ul>
                
                <p><strong>Access Instructions:</strong> You will receive a video call link via SMS or you can access it through our patient portal.</p>
                
                <p>If you need to reschedule or cancel, please contact us at least 24 hours in advance.</p>
            </div>
            <div class='footer'>
                <p>This is an automated reminder. Please do not reply to this email.</p>
                <p>&copy; " . date('Y') . " ENT Hospital. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>
    ";
    
    try {
        // Send email using PHPMailer
        $email_result = sendEmail($appointment['patient_email'], $subject, $email_body);
        if ($email_result['success']) {
            $email_sent = true;
            $messages[] = 'Email sent successfully';
        } else {
            $messages[] = 'Email failed: ' . $email_result['message'];
        }
    } catch (Exception $e) {
        $messages[] = 'Email error: ' . $e->getMessage();
    }
}

// Log the reminder activity
$log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
           VALUES (?, 'SEND_REMINDER', 'TELEMEDICINE', ?, 'APPOINTMENT', ?, NOW())";
$log_stmt = $conn->prepare($log_sql);
$ip_address = $_SERVER['REMOTE_ADDR'];
$log_stmt->bind_param('iis', $user_id, $appointment_id, $ip_address);
$log_stmt->execute();

// Log communication
$comm_sql = "INSERT INTO communication_log (appointment_id, patient_id, communication_type, recipient, message, status, sent_at)
            VALUES (?, ?, ?, ?, ?, 'SENT', NOW())";

if ($sms_sent) {
    $comm_stmt = $conn->prepare($comm_sql);
    $comm_type = 'SMS';
    $sms_message = "Appointment reminder sent";
    $comm_stmt->bind_param('iisss', $appointment_id, $appointment['patient_id'], $comm_type, $appointment['patient_phone'], $sms_message);
    $comm_stmt->execute();
}

if ($email_sent) {
    $comm_stmt = $conn->prepare($comm_sql);
    $comm_type = 'EMAIL';
    $email_message = "Appointment reminder sent";
    $comm_stmt->bind_param('iisss', $appointment_id, $appointment['patient_id'], $comm_type, $appointment['patient_email'], $email_message);
    $comm_stmt->execute();
}

$conn->close();

// Return response
if ($sms_sent || $email_sent) {
    echo json_encode([
        'success' => true,
        'message' => 'Reminder sent successfully: ' . implode(', ', $messages),
        'sms_sent' => $sms_sent,
        'email_sent' => $email_sent
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to send reminder. ' . implode(', ', $messages),
        'sms_sent' => false,
        'email_sent' => false
    ]);
}
?>