<?php
session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch system settings for SMS
function getSetting($conn, $key) {
    $sql = "SELECT setting_value FROM system_settings WHERE setting_key = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    return $row['setting_value'] ?? '';
}

$sms_enabled = getSetting($conn, 'sms_enabled');

// Fetch SMS templates
$templates_sql = "SELECT * FROM communication_templates 
                  WHERE template_type = 'SMS' AND is_active = 1 
                  ORDER BY category";
$templates_result = $conn->query($templates_sql);

// Fetch recent SMS logs
$logs_sql = "SELECT cl.*, 
             CASE 
                 WHEN cl.recipient_type = 'PATIENT' THEN CONCAT(u.first_name, ' ', u.last_name)
                 ELSE 'Staff'
             END as recipient_name
             FROM communication_log cl
             LEFT JOIN patients p ON cl.recipient_id = p.patient_id AND cl.recipient_type = 'PATIENT'
             LEFT JOIN users u ON p.user_id = u.user_id
             WHERE cl.communication_type = 'SMS'
             ORDER BY cl.created_at DESC
             LIMIT 50";
$logs_result = $conn->query($logs_sql);

// Get SMS statistics
$stats_sql = "SELECT 
              COUNT(*) as total_sms,
              SUM(CASE WHEN status = 'SENT' THEN 1 ELSE 0 END) as sent,
              SUM(CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END) as delivered,
              SUM(CASE WHEN status = 'FAILED' THEN 1 ELSE 0 END) as failed,
              SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today,
              SUM(cost) as total_cost
              FROM communication_log 
              WHERE communication_type = 'SMS'";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Handle manual SMS send
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_sms'])) {
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $recipient_type = $_POST['recipient_type'] ?? 'EXTERNAL';
    $recipient_id = $_POST['recipient_id'] ?? 0;
    
    // Send SMS via Africa's Talking
    $result = sendSMS($conn, $phone, $message, $recipient_type, $recipient_id);
    
    if ($result['success']) {
        $success_message = "SMS sent successfully to " . $phone;
    } else {
        $error_message = "Failed to send SMS: " . $result['message'];
    }
}

function sendSMS($conn, $phone, $message, $recipient_type = 'EXTERNAL', $recipient_id = 0) {
    // Get SMS settings
    $api_username = getSetting($conn, 'sms_api_username');
    $api_key = getSetting($conn, 'sms_api_key');
    $sender_id = getSetting($conn, 'sms_sender_id');
    
    if (empty($api_username) || empty($api_key)) {
        return ['success' => false, 'message' => 'SMS not configured'];
    }
    
    // Format phone number
    $phone = preg_replace('/[^0-9+]/', '', $phone);
    if (!str_starts_with($phone, '+')) {
        $phone = '+254' . ltrim($phone, '0');
    }
    
    // Prepare API request
    $api_url = "https://api.africastalking.com/version1/messaging";
    
    $post_data = [
        'username' => $api_username,
        'to' => $phone,
        'message' => $message,
        'from' => $sender_id
    ];
    
    // Send SMS
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $api_url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($post_data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'apiKey: ' . $api_key,
            'Content-Type: application/x-www-form-urlencoded',
            'Accept: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 30
    ]);
    
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    $result = json_decode($response, true);
    
    // Log SMS
    if ($http_code === 201 || ($http_code === 200 && isset($result['SMSMessageData']))) {
        $recipients = $result['SMSMessageData']['Recipients'] ?? [];
        
        if (!empty($recipients) && $recipients[0]['statusCode'] == 101) {
            $cost = floatval(str_replace('KES ', '', $recipients[0]['cost'] ?? '0'));
            $message_id = $recipients[0]['messageId'] ?? '';
            
            $log_sql = "INSERT INTO communication_log (recipient_type, recipient_id, communication_type, 
                       message, recipient_contact, status, external_id, cost, sent_by, sent_at) 
                       VALUES (?, ?, 'SMS', ?, ?, 'SENT', ?, ?, ?, NOW())";
            $stmt = $conn->prepare($log_sql);
            $stmt->bind_param("sissdi", $recipient_type, $recipient_id, $message, $phone, 
                             $message_id, $cost, $_SESSION['user_id']);
            $stmt->execute();
            
            return ['success' => true, 'message' => 'SMS sent successfully', 'cost' => $cost];
        }
    }
    
    return ['success' => false, 'message' => 'Failed to send SMS'];
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'SMS Integration')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .sms-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
        }
        
        .stats-card {
            text-align: center;
            padding: 1.5rem;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            background: white;
        }
        
        .stats-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stats-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
        }
        
        .template-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .template-card:hover {
            border-color: #059669;
            background: #f0fdf4;
        }
        
        .sms-preview {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            font-family: monospace;
            min-height: 100px;
        }
        
        .char-count {
            text-align: right;
            font-size: 0.875rem;
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        .sms-log-item {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .sms-log-item:last-child {
            border-bottom: none;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-sent { background: #dcfce7; color: #166534; }
        .status-delivered { background: #dbeafe; color: #1e40af; }
        .status-failed { background: #fee2e2; color: #991b1b; }
        .status-pending { background: #fef3c7; color: #92400e; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">SMS Notification Center</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Communication</li>
                                        <li class="breadcrumb-item active">SMS Integration</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($sms_enabled != '1'): ?>
                    <div class="alert alert-warning">
                        <i class="ri-alert-line me-2"></i>
                        <strong>SMS Integration Disabled</strong><br>
                        Please enable and configure SMS in <a href="system_settings.php#sms">System Settings</a>
                    </div>
                    <?php endif; ?>

                    <?php if (isset($success_message)): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="ri-check-line me-2"></i><?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="stats-value text-primary"><?php echo number_format($stats['total_sms']); ?></div>
                                <div class="stats-label">Total SMS</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="stats-value text-success"><?php echo number_format($stats['sent']); ?></div>
                                <div class="stats-label">Sent</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="stats-value text-info"><?php echo number_format($stats['today']); ?></div>
                                <div class="stats-label">Today</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="stats-value text-warning">KES <?php echo number_format($stats['total_cost'], 2); ?></div>
                                <div class="stats-label">Total Cost</div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Send SMS Form -->
                        <div class="col-lg-8">
                            <div class="sms-card">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">
                                        <i class="ri-message-2-line me-2"></i>Send SMS
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    <form method="POST" id="smsForm">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Recipient Type</label>
                                                <select class="form-select" id="recipientType" name="recipient_type">
                                                    <option value="EXTERNAL">Manual Entry</option>
                                                    <option value="PATIENT">Select Patient</option>
                                                    <option value="STAFF">Select Staff</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Phone Number *</label>
                                                <input type="tel" class="form-control" name="phone" id="phoneNumber" 
                                                       placeholder="+254700000000" required>
                                                <div class="help-text">Format: +254700000000 or 0700000000</div>
                                            </div>
                                        </div>

                                        <!-- Patient Selection (Hidden by default) -->
                                        <div class="mb-3" id="patientSelection" style="display:none;">
                                            <label class="form-label">Select Patient</label>
                                            <select class="form-select" id="patientSelect">
                                                <option value="">Choose patient...</option>
                                                <?php
                                                $patients_sql = "SELECT p.patient_id, u.first_name, u.last_name, u.phone_primary, p.patient_number
                                                                FROM patients p
                                                                INNER JOIN users u ON p.user_id = u.user_id
                                                                WHERE p.is_active = 1
                                                                ORDER BY u.first_name";
                                                $patients = $conn->query($patients_sql);
                                                while($patient = $patients->fetch_assoc()):
                                                ?>
                                                <option value="<?php echo $patient['patient_id']; ?>" 
                                                        data-phone="<?php echo $patient['phone_primary']; ?>">
                                                    <?php echo $patient['first_name'] . ' ' . $patient['last_name']; ?> - 
                                                    <?php echo $patient['patient_number']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Message *</label>
                                            <textarea class="form-control" name="message" id="smsMessage" 
                                                      rows="4" maxlength="480" required
                                                      placeholder="Type your message here..."></textarea>
                                            <div class="char-count">
                                                <span id="charCount">0</span> / 480 characters 
                                                (<span id="smsCount">0</span> SMS)
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Preview</label>
                                            <div class="sms-preview" id="smsPreview">
                                                <em class="text-muted">Your message will appear here...</em>
                                            </div>
                                        </div>

                                        <div class="d-flex gap-2">
                                            <button type="submit" name="send_sms" class="btn btn-success">
                                                <i class="ri-send-plane-line me-1"></i> Send SMS
                                            </button>
                                            <button type="button" class="btn btn-outline-secondary" onclick="clearForm()">
                                                <i class="ri-refresh-line me-1"></i> Clear
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- SMS Templates -->
                            <div class="sms-card">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">
                                        <i class="ri-file-list-line me-2"></i>SMS Templates
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    <?php if ($templates_result->num_rows > 0): ?>
                                        <?php while($template = $templates_result->fetch_assoc()): ?>
                                        <div class="template-card" onclick="useTemplate('<?php echo htmlspecialchars($template['content']); ?>')">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h6 class="mb-1"><?php echo $template['template_name']; ?></h6>
                                                    <small class="text-muted"><?php echo ucfirst($template['category']); ?></small>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-outline-primary">
                                                    Use Template
                                                </button>
                                            </div>
                                            <p class="text-muted small mt-2 mb-0">
                                                <?php echo substr($template['content'], 0, 100); ?>...
                                            </p>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <p class="text-muted text-center py-4">No templates available</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- SMS Log Sidebar -->
                        <div class="col-lg-4">
                            <div class="sms-card">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">
                                        <i class="ri-history-line me-2"></i>Recent SMS
                                    </h5>
                                </div>
                                <div class="card-body p-0" style="max-height: 800px; overflow-y: auto;">
                                    <?php if ($logs_result->num_rows > 0): ?>
                                        <?php while($log = $logs_result->fetch_assoc()): ?>
                                        <div class="sms-log-item">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <div>
                                                    <h6 class="mb-1"><?php echo $log['recipient_name'] ?? 'Unknown'; ?></h6>
                                                    <small class="text-muted"><?php echo $log['recipient_contact']; ?></small>
                                                </div>
                                                <?php
                                                $status_class = match($log['status']) {
                                                    'SENT' => 'status-sent',
                                                    'DELIVERED' => 'status-delivered',
                                                    'FAILED' => 'status-failed',
                                                    default => 'status-pending'
                                                };
                                                ?>
                                                <span class="status-badge <?php echo $status_class; ?>">
                                                    <?php echo ucfirst(strtolower($log['status'])); ?>
                                                </span>
                                            </div>
                                            <p class="text-muted small mb-1">
                                                <?php echo substr($log['message'], 0, 100); ?>
                                                <?php if (strlen($log['message']) > 100): ?>...<?php endif; ?>
                                            </p>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <small class="text-muted">
                                                    <?php echo date('M j, g:i A', strtotime($log['created_at'])); ?>
                                                </small>
                                                <?php if ($log['cost'] > 0): ?>
                                                <small class="text-muted">KES <?php echo number_format($log['cost'], 2); ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center text-muted p-4">
                                            <i class="ri-message-2-line display-4 mb-3"></i>
                                            <p>No SMS history</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="sms-card">
                                <div class="card-header bg-light">
                                    <h5 class="mb-0">Quick Actions</h5>
                                </div>
                                <div class="card-body p-3">
                                    <a href="api/send_appointment_reminders.php" class="btn btn-outline-primary w-100 mb-2">
                                        <i class="ri-calendar-line me-1"></i> Send Appointment Reminders
                                    </a>
                                    <a href="api/send_bulk_sms.php" class="btn btn-outline-success w-100 mb-2">
                                        <i class="ri-group-line me-1"></i> Send Bulk SMS
                                    </a>
                                    <a href="communication_log.php?type=SMS" class="btn btn-outline-info w-100">
                                        <i class="ri-file-list-3-line me-1"></i> View Full SMS Log
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Character counter
            $('#smsMessage').on('input', function() {
                const message = $(this).val();
                const charCount = message.length;
                const smsCount = Math.ceil(charCount / 160);
                
                $('#charCount').text(charCount);
                $('#smsCount').text(smsCount);
                $('#smsPreview').text(message || 'Your message will appear here...');
            });
            
            // Recipient type change
            $('#recipientType').on('change', function() {
                if ($(this).val() === 'PATIENT') {
                    $('#patientSelection').show();
                } else {
                    $('#patientSelection').hide();
                    $('#phoneNumber').val('');
                }
            });
            
            // Patient selection
            $('#patientSelect').on('change', function() {
                const phone = $(this).find(':selected').data('phone');
                $('#phoneNumber').val(phone);
            });
            
            // Form validation
            $('#smsForm').on('submit', function(e) {
                const phone = $('#phoneNumber').val();
                const message = $('#smsMessage').val();
                
                if (!phone || !message) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Missing Information',
                        text: 'Please enter phone number and message'
                    });
                    return false;
                }
                
                // Show confirmation
                e.preventDefault();
                Swal.fire({
                    title: 'Send SMS?',
                    html: 'Send message to <strong>' + phone + '</strong>?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Send SMS',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        this.submit();
                    }
                });
            });
        });
        
        // Use template
        function useTemplate(content) {
            $('#smsMessage').val(content).trigger('input');
            
            Swal.fire({
                icon: 'success',
                title: 'Template Loaded',
                text: 'You can now edit the message',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 2000
            });
        }
        
        // Clear form
        function clearForm() {
            $('#smsForm')[0].reset();
            $('#charCount').text('0');
            $('#smsCount').text('0');
            $('#smsPreview').html('<em class="text-muted">Your message will appear here...</em>');
            $('#patientSelection').hide();
        }
    </script>
</body>
</html>