<?php
/**
 * ajax/send_telemedicine_reminder.php
 * Sends an SMS (Africa's Talking) + Email (PHPMailer) reminder
 * to a patient for their upcoming telemedicine appointment.
 *
 * POST body: JSON { "appointment_id": 123 }
 * Returns  : JSON { success, message, sms_sent, email_sent, errors[] }
 */

session_start();
header('Content-Type: application/json');

require_once '../layouts/dbconn.php';
require_once '../layouts/session.php';

// PHPMailer — must be at file scope
require_once '../vendor/phpmailer/src/PHPMailer.php';
require_once '../vendor/phpmailer/src/SMTP.php';
require_once '../vendor/phpmailer/src/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;

// ── Auth ──────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$allowed_roles = ['SUPER_ADMIN','HOSPITAL_ADMIN','MEDICAL_DIRECTOR','ENT_CONSULTANT',
                  'ENT_DOCTOR','RESIDENT_DOCTOR','HEAD_NURSE','RECEPTIONIST','FRONT_OFFICE'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit();
}

// ── Parse input ───────────────────────────────────────────────────────
$input          = json_decode(file_get_contents('php://input'), true) ?: [];
$appointment_id = (int)($input['appointment_id'] ?? 0);

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

// ── Fetch appointment + patient contact ───────────────────────────────
$stmt = $conn->prepare("
    SELECT a.appointment_id, a.appointment_number,
           a.appointment_date, a.appointment_time, a.status,
           pu.full_name AS patient_name, pu.phone_primary, pu.email,
           du.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 du   ON a.doctor_id   = du.user_id
    WHERE a.appointment_id = ? AND a.appointment_type = 'TELEMEDICINE'");
$stmt->bind_param('i', $appointment_id);
$stmt->execute();
$appt = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$appt) {
    echo json_encode(['success' => false, 'message' => 'Telemedicine appointment not found']);
    exit();
}

// ── Build meeting URL (same deterministic formula as telemedicine.php) ─
$JITSI_SERVER = 'https://meet.jit.si';
$room_name    = 'ProdigyENT_' . preg_replace('/[^a-zA-Z0-9]/', '_', $appt['appointment_number']);
$meeting_url  = $JITSI_SERVER . '/' . $room_name;

$date_str = date('d M Y',  strtotime($appt['appointment_date']));
$time_str = date('h:i A',  strtotime($appt['appointment_time']));

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

// ── Fetch SMS settings ────────────────────────────────────────────────
$stmt = $conn->prepare("SELECT setting_key, setting_value FROM system_settings WHERE category='sms'");
$stmt->execute();
$sms_cfg = [];
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) { $sms_cfg[$r['setting_key']] = $r['setting_value']; }
$stmt->close();

// ── Send SMS via Africa's Talking ─────────────────────────────────────
if (!empty($sms_cfg['at_api_key']) && !empty($appt['phone_primary'])) {
    $phone = $appt['phone_primary'];
    $phone = preg_replace('/^0/',   '+254', $phone);
    $phone = preg_replace('/^254/', '+254', $phone);

    $sms_body = "Reminder: Your Prodigy ENT telemedicine appointment with Dr. "
              . $appt['doctor_name'] . " is on $date_str at $time_str.\n"
              . "Join here: $meeting_url\n"
              . "No app needed - open in any browser.";

    $at_data = http_build_query([
        'username' => $sms_cfg['at_username'] ?? 'sandbox',
        'to'       => $phone,
        'message'  => $sms_body,
        'from'     => $sms_cfg['at_sender_id'] ?? 'ProdigyENT',
    ]);

    $ch = curl_init('https://api.africastalking.com/version1/messaging');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $at_data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'apiKey: ' . $sms_cfg['at_api_key'],
            'Accept: application/json',
            'Content-Type: application/x-www-form-urlencoded',
        ],
        CURLOPT_TIMEOUT => 10,
    ]);
    $at_response = curl_exec($ch);
    $at_error    = curl_error($ch);
    curl_close($ch);

    if (!$at_error) {
        $at_result = json_decode($at_response, true);
        $sms_sent  = isset($at_result['SMSMessageData']['Recipients'][0]['status'])
                  && $at_result['SMSMessageData']['Recipients'][0]['status'] === 'Success';
        if (!$sms_sent) {
            $errors[] = 'SMS: ' . ($at_result['SMSMessageData']['Message'] ?? 'Unknown AT error');
        }
    } else {
        $errors[] = 'SMS cURL: ' . $at_error;
    }
} else {
    if (empty($sms_cfg['at_api_key'])) { $errors[] = 'SMS: Africa\'s Talking not configured'; }
    if (empty($appt['phone_primary'])) { $errors[] = 'SMS: Patient has no phone number on file'; }
}

// ── Fetch Email settings ──────────────────────────────────────────────
$stmt = $conn->prepare("SELECT setting_key, setting_value FROM system_settings WHERE category='email'");
$stmt->execute();
$email_cfg = [];
$res = $stmt->get_result();
while ($r = $res->fetch_assoc()) { $email_cfg[$r['setting_key']] = $r['setting_value']; }
$stmt->close();

// ── Send Email via PHPMailer ──────────────────────────────────────────
if (!empty($appt['email'])) {
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = $email_cfg['smtp_host']      ?? 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = $email_cfg['smtp_username']  ?? '';
        $mail->Password   = $email_cfg['smtp_password']  ?? '';
        $mail->SMTPSecure = $email_cfg['smtp_encryption'] ?? 'tls';
        $mail->Port       = (int)($email_cfg['smtp_port'] ?? 587);

        $mail->setFrom(
            $email_cfg['from_email'] ?? $mail->Username,
            $email_cfg['from_name']  ?? 'Prodigy ENT Hospital'
        );
        $mail->addAddress($appt['email'], $appt['patient_name']);
        $mail->isHTML(true);
        $mail->Subject = 'Appointment Reminder — Telemedicine on ' . $date_str . ' | Prodigy ENT';

        $mail->Body = '
        <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;background:#f9fafb;padding:20px;border-radius:12px;">

            <!-- Header -->
            <div style="background:linear-gradient(135deg,#8FBC8F,#20B2AA);border-radius:10px;padding:24px;text-align:center;margin-bottom:20px;">
                <h2 style="color:white;margin:0 0 4px;">&#x1F4C5; Appointment Reminder</h2>
                <p style="color:rgba(255,255,255,.88);margin:0;font-size:14px;">Prodigy ENT Specialist Hospital — Telemedicine</p>
            </div>

            <!-- Body -->
            <div style="background:white;border-radius:10px;padding:24px;border:1px solid #e5e7eb;">
                <p style="font-size:16px;margin-top:0;">Dear <strong>' . htmlspecialchars($appt['patient_name']) . '</strong>,</p>
                <p style="color:#475569;">This is a reminder for your upcoming telemedicine consultation:</p>

                <!-- Appointment details box -->
                <table style="width:100%;border-collapse:collapse;margin:16px 0;font-size:14px;">
                    <tr style="background:#f0fdf4;">
                        <td style="padding:10px 14px;border:1px solid #d1fae5;font-weight:600;color:#065f46;width:40%;">Doctor</td>
                        <td style="padding:10px 14px;border:1px solid #d1fae5;color:#1e293b;">Dr. ' . htmlspecialchars($appt['doctor_name']) . '</td>
                    </tr>
                    <tr>
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;font-weight:600;color:#374151;">Date</td>
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;color:#1e293b;">' . $date_str . '</td>
                    </tr>
                    <tr style="background:#f9fafb;">
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;font-weight:600;color:#374151;">Time</td>
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;color:#1e293b;font-weight:700;">' . $time_str . '</td>
                    </tr>
                    <tr>
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;font-weight:600;color:#374151;">Reference</td>
                        <td style="padding:10px 14px;border:1px solid #e5e7eb;color:#20B2AA;font-weight:600;">' . htmlspecialchars($appt['appointment_number']) . '</td>
                    </tr>
                </table>

                <!-- Join button -->
                <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:20px;text-align:center;margin:20px 0;">
                    <p style="margin:0 0 14px;font-weight:700;color:#065f46;font-size:15px;">When it is time, click the button below to join:</p>
                    <a href="' . $meeting_url . '"
                       style="background:linear-gradient(135deg,#8FBC8F,#20B2AA);color:white;text-decoration:none;
                              padding:14px 32px;border-radius:8px;font-weight:700;font-size:16px;display:inline-block;">
                        &#x1F4F9;&nbsp; Join Video Consultation
                    </a>
                    <p style="margin:14px 0 0;font-size:12px;color:#6b7280;">
                        Or copy this link:<br>
                        <a href="' . $meeting_url . '" style="color:#20B2AA;word-break:break-all;">' . $meeting_url . '</a>
                    </p>
                </div>

                <!-- Tips -->
                <div style="background:#eff6ff;border-radius:8px;padding:14px;font-size:13px;color:#1e40af;">
                    <strong>&#x2139;&#xFE0F; Tips for a smooth call:</strong>
                    <ul style="margin:6px 0 0;padding-left:18px;line-height:1.8;">
                        <li>Use Chrome or Firefox for best experience</li>
                        <li>Allow camera &amp; microphone access when prompted</li>
                        <li>Join from a quiet, well-lit place</li>
                        <li>No app download required — works in your browser</li>
                    </ul>
                </div>

                <hr style="border:none;border-top:1px solid #e5e7eb;margin:20px 0;">
                <p style="font-size:12px;color:#94a3b8;margin:0;text-align:center;">
                    Prodigy ENT Specialist Hospital &nbsp;&bull;&nbsp; Nairobi, Kenya<br>
                    If you need to reschedule, please call us.
                </p>
            </div>
        </div>';

        $mail->AltBody = "Appointment Reminder\n\n"
            . "Dear {$appt['patient_name']},\n\n"
            . "Your telemedicine appointment with Dr. {$appt['doctor_name']} is on $date_str at $time_str.\n\n"
            . "Join here: $meeting_url\n\n"
            . "No app needed - open in any browser.\n\n"
            . "Prodigy ENT Specialist Hospital";

        $mail->send();
        $email_sent = true;

    } catch (MailException $e) {
        $errors[] = 'Email: ' . $e->getMessage();
    }
} else {
    $errors[] = 'Email: Patient has no email address on file';
}

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

// ── Build response message ────────────────────────────────────────────
$sent_parts = [];
if ($sms_sent)   { $sent_parts[] = 'SMS'; }
if ($email_sent) { $sent_parts[] = 'Email'; }

if (!empty($sent_parts)) {
    $message = 'Reminder sent via ' . implode(' & ', $sent_parts) . ' to ' . $appt['patient_name'];
} elseif (!empty($errors)) {
    $message = 'Could not send reminder: ' . implode('; ', $errors);
} else {
    $message = 'No contact information available for this patient';
}

echo json_encode([
    'success'     => $sms_sent || $email_sent,
    'message'     => $message,
    'sms_sent'    => $sms_sent,
    'email_sent'  => $email_sent,
    'errors'      => $errors,
    'meeting_url' => $meeting_url,
]);