<?php
/**
 * Send Reminder
 * Send SMS or Email reminder to patient
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$reminderId = (int)($_GET['id'] ?? 0);
$type = $_GET['type'] ?? 'sms'; // sms or email
$error = '';
$success = '';

// Get case details
$stmt = $pdo->prepare("SELECT c.id, c.patient_name, c.patient_mobile, c.follow_up_date, 
                      c.prescribed_remedy_id, c.prescription_potency,
                      r.name as remedy_name, u.full_name as doctor_name
                      FROM cases c
                      LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                      JOIN users u ON c.user_id = u.id
                      WHERE c.id = ? AND c.user_id = ?");
$stmt->execute([$reminderId, $userId]);
$case = $stmt->fetch();

if (!$case) {
    header('Location: index.php?error=Reminder not found');
    exit;
}

// Prepare message templates
$date = date('d-m-Y', strtotime($case['follow_up_date']));
$doctorName = $case['doctor_name'];
$patientName = $case['patient_name'];

$smsTemplate = "Dear $patientName, this is a reminder from Dr. $doctorName for your follow-up appointment on $date. Please contact us if you need to reschedule. Thank you.";

$emailTemplate = "Dear $patientName,\n\n";
$emailTemplate .= "This is a friendly reminder from Dr. $doctorName for your follow-up appointment scheduled on $date.\n\n";
if ($case['remedy_name']) {
    $emailTemplate .= "Current prescription: {$case['remedy_name']} ({$case['prescription_potency']})\n\n";
}
$emailTemplate .= "Please contact our clinic if you need to reschedule or have any questions.\n\n";
$emailTemplate .= "Best regards,\n";
$emailTemplate .= "Dr. $doctorName\n";
$emailTemplate .= APP_NAME;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $message = $_POST['message'];
    $mobile = $_POST['mobile'];
    $email = $_POST['email'];
    $sendMethod = $_POST['send_method'];
    
    $sent = false;
    
    if ($sendMethod == 'sms') {
        // Send SMS (using SMS API - configure in settings)
        // This is a placeholder - integrate with your SMS provider
        $smsSent = sendSMS($mobile, $message);
        if ($smsSent) {
            $success = "SMS reminder sent successfully to $mobile!";
            $sent = true;
        } else {
            $error = "Failed to send SMS. Please check SMS gateway configuration.";
        }
    } elseif ($sendMethod == 'email') {
        // Send Email
        $emailSent = sendEmail($email, "Follow-up Reminder - Dr. $doctorName", $message);
        if ($emailSent) {
            $success = "Email reminder sent successfully to $email!";
            $sent = true;
        } else {
            $error = "Failed to send email. Please check email configuration.";
        }
    }
    
    if ($sent) {
        // Log the reminder
        $stmt = $pdo->prepare("INSERT INTO reminder_logs (case_id, type, recipient, message, sent_at) 
                              VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$reminderId, $sendMethod, ($sendMethod == 'sms' ? $mobile : $email), $message]);
        
        header("refresh:2;url=index.php");
    }
}

// Helper function to send SMS (implement based on your SMS provider)
function sendSMS($mobile, $message) {
    // Example with TextLocal API (configure in settings)
    // $apiKey = SMS_API_KEY;
    // $sender = 'HOMEO';
    // $url = "https://api.textlocal.in/send/";
    // ... implement SMS sending
    
    // For now, simulate success
    return true;
}

// Get reminder log history
$stmt = $pdo->prepare("SELECT * FROM reminder_logs WHERE case_id = ? ORDER BY sent_at DESC");
$stmt->execute([$reminderId]);
$logs = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Reminder - <?php echo APP_NAME; ?></title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); }
        .sidebar .nav-link.active { background: #2ecc71; }
        .sidebar .nav-link i { margin-right: 10px; }
        .main-content { margin-left: 260px; padding: 20px; }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .message-preview {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            font-family: monospace;
            white-space: pre-wrap;
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center py-4"><h4 class="text-white mb-0">🏥</h4></div>
        <nav class="nav flex-column">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="../cases/index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link" href="../materia-medica/index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-bell"></i> <span>Reminders</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr><a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-paper-plane"></i> Send Reminder - <?php echo escape($case['patient_name']); ?></h4>
                <a href="index.php" class="btn btn-secondary btn-sm">Back to Reminders</a>
            </div>
        </div>
        
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-7">
                <div class="form-card">
                    <h5><i class="fas fa-pencil-alt"></i> Compose Message</h5>
                    <form method="POST" id="sendForm">
                        <div class="mb-3">
                            <label class="form-label">Send Method</label>
                            <div class="btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="send_method" id="smsRadio" value="sms" 
                                       <?php echo $type == 'sms' ? 'checked' : ''; ?> autocomplete="off">
                                <label class="btn btn-outline-primary" for="smsRadio">
                                    <i class="fas fa-sms"></i> SMS
                                </label>
                                
                                <input type="radio" class="btn-check" name="send_method" id="emailRadio" value="email" 
                                       <?php echo $type == 'email' ? 'checked' : ''; ?> autocomplete="off">
                                <label class="btn btn-outline-primary" for="emailRadio">
                                    <i class="fas fa-envelope"></i> Email
                                </label>
                            </div>
                        </div>
                        
                        <div class="mb-3" id="mobileField">
                            <label for="mobile" class="form-label">Mobile Number</label>
                            <input type="tel" name="mobile" id="mobile" class="form-control" 
                                   value="<?php echo $case['patient_mobile']; ?>" required>
                        </div>
                        
                        <div class="mb-3" id="emailField" style="display: none;">
                            <label for="email" class="form-label">Email Address</label>
                            <input type="email" name="email" id="email" class="form-control" 
                                   placeholder="patient@example.com" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="message" class="form-label">Message</label>
                            <textarea name="message" id="message" class="form-control" rows="8" required></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-paper-plane"></i> Send Reminder
                        </button>
                    </form>
                </div>
            </div>
            
            <div class="col-md-5">
                <div class="form-card">
                    <h6><i class="fas fa-info-circle"></i> Patient Information</h6>
                    <hr>
                    <p><strong>Patient:</strong> <?php echo escape($case['patient_name']); ?></p>
                    <p><strong>Mobile:</strong> <?php echo $case['patient_mobile']; ?></p>
                    <p><strong>Follow-up Date:</strong> <?php echo date('d-m-Y', strtotime($case['follow_up_date'])); ?></p>
                    <?php if($case['remedy_name']): ?>
                        <p><strong>Prescription:</strong> <?php echo escape($case['remedy_name']); ?> (<?php echo $case['prescription_potency']; ?>)</p>
                    <?php endif; ?>
                </div>
                
                <div class="form-card">
                    <h6><i class="fas fa-file-alt"></i> Message Preview</h6>
                    <hr>
                    <div class="message-preview" id="messagePreview">
                        Loading...
                    </div>
                </div>
                
                <?php if(!empty($logs)): ?>
                <div class="form-card">
                    <h6><i class="fas fa-history"></i> Reminder History</h6>
                    <hr>
                    <div class="small">
                        <?php foreach(array_slice($logs, 0, 5) as $log): ?>
                            <div class="border-bottom pb-2 mb-2">
                                <strong><?php echo date('d-m-Y H:i', strtotime($log['sent_at'])); ?></strong><br>
                                <span class="badge bg-<?php echo $log['type'] == 'sms' ? 'primary' : 'success'; ?>">
                                    <?php echo strtoupper($log['type']); ?>
                                </span>
                                <span class="text-muted">to: <?php echo $log['recipient']; ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Toggle between SMS and Email fields
        function toggleFields() {
            if ($('#smsRadio').is(':checked')) {
                $('#mobileField').show();
                $('#emailField').hide();
                $('#mobile').prop('required', true);
                $('#email').prop('required', false);
                updatePreview('sms');
            } else {
                $('#mobileField').hide();
                $('#emailField').show();
                $('#mobile').prop('required', false);
                $('#email').prop('required', true);
                updatePreview('email');
            }
        }
        
        // Update message preview
        function updatePreview(type) {
            let preview = '';
            const patientName = "<?php echo addslashes($case['patient_name']); ?>";
            const doctorName = "<?php echo addslashes($case['doctor_name']); ?>";
            const date = "<?php echo date('d-m-Y', strtotime($case['follow_up_date'])); ?>";
            const remedy = "<?php echo addslashes($case['remedy_name'] ?? ''); ?>";
            const potency = "<?php echo addslashes($case['prescription_potency'] ?? ''); ?>";
            
            if (type === 'sms') {
                preview = `Dear ${patientName}, this is a reminder from Dr. ${doctorName} for your follow-up appointment on ${date}. Please contact us if you need to reschedule. Thank you.`;
            } else {
                preview = `Dear ${patientName},\n\n`;
                preview += `This is a friendly reminder from Dr. ${doctorName} for your follow-up appointment scheduled on ${date}.\n\n`;
                if (remedy) {
                    preview += `Current prescription: ${remedy} (${potency})\n\n`;
                }
                preview += `Please contact our clinic if you need to reschedule or have any questions.\n\n`;
                preview += `Best regards,\n`;
                preview += `Dr. ${doctorName}\n`;
                preview += `<?php echo APP_NAME; ?>`;
            }
            
            $('#message').val(preview);
            $('#messagePreview').text(preview);
        }
        
        // Initialize
        $('input[name="send_method"]').on('change', function() {
            toggleFields();
        });
        
        // Update preview when message changes
        $('#message').on('input', function() {
            $('#messagePreview').text($(this).val());
        });
        
        toggleFields();
    </script>
</body>
</html>