<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.php';
require_once '../includes/sidebar_layout.php';

// Check if user is logged in and has admin permission
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit();
}

// Get system name for branding
$system_name = get_system_name($pdo);

// Load current messaging configuration
$config = [
    'auto_message_enabled' => true,
    'message_template' => 'আপনার সন্তান {student_name} এর উপস্থিতি সফলভাবে রেকর্ড করা হয়েছে। তারিখ: {date}',
    'sms_gateway' => 'non_musking', // Options: non_musking, other_gateways
    'send_to_guardian' => true,
    'send_to_student' => false, // For students who have phone numbers
    'send_time_delay' => 5, // minutes delay before sending
];

// Load existing configuration from database if it exists
try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM attendance_settings WHERE setting_key IN ('auto_message_enabled', 'message_template', 'sms_gateway', 'send_to_guardian', 'send_to_student', 'send_time_delay')");
    $db_config = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    foreach ($db_config as $key => $value) {
        if (array_key_exists($key, $config)) {
            // Handle boolean values
            if (in_array($key, ['auto_message_enabled', 'send_to_guardian', 'send_to_student'])) {
                $config[$key] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
            } else {
                $config[$key] = $value;
            }
        }
    }
} catch (Exception $e) {
    // If settings table doesn't exist, use defaults
}

$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $config['auto_message_enabled'] = isset($_POST['auto_message_enabled']);
    $config['message_template'] = $_POST['message_template'];
    $config['sms_gateway'] = $_POST['sms_gateway'];
    $config['send_to_guardian'] = isset($_POST['send_to_guardian']);
    $config['send_to_student'] = isset($_POST['send_to_student']);
    $config['send_time_delay'] = (int)$_POST['send_time_delay'];

    // Save settings to database
    $stmt = $pdo->prepare("INSERT INTO attendance_settings (setting_key, setting_value, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    
    $settings = [
        ['auto_message_enabled', $config['auto_message_enabled'] ? '1' : '0', 'Enable auto messaging for attendance'],
        ['message_template', $config['message_template'], 'Template for attendance messages'],
        ['sms_gateway', $config['sms_gateway'], 'SMS gateway to use for messaging'],
        ['send_to_guardian', $config['send_to_guardian'] ? '1' : '0', 'Send message to guardian'],
        ['send_to_student', $config['send_to_student'] ? '1' : '0', 'Send message to student'],
        ['send_time_delay', $config['send_time_delay'], 'Delay in minutes before sending message']
    ];

    foreach ($settings as $setting) {
        $stmt->execute($setting);
    }
    
    $success_message = 'মেসেজিং কনফিগারেশন সফলভাবে সংরক্ষণ করা হয়েছে';
}

// Get user info for sidebar
$user_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'User';
if (isset($_SESSION['user_id'])) {
    if ($_SESSION['user_role'] == 'teacher') {
        $stmt = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM teachers WHERE user_id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $result = $stmt->fetch();
        if ($result) {
            $user_name = $result['name'];
        }
    }
}

$current_page = basename($_SERVER['PHP_SELF']);
$sidebar_html = renderSidebar($current_page, $_SESSION['user_role'], $user_name);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মেসেজিং কনফিগারেশন - <?php echo htmlspecialchars($system_name); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .config-card {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        
        .message-preview {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 15px;
            margin-top: 10px;
        }
        
        .variable-help {
            background-color: #e7f5ff;
            border-left: 4px solid #339af0;
            padding: 10px;
            margin-top: 10px;
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="sidebar-container">
        <?php echo $sidebar_html; ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-comment-dots me-2"></i>
                    মেসেজিং কনফিগারেশন
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / মেসেজিং কনফিগারেশন
                    <span class="ms-3 text-muted">
                        <i class="fas fa-clock me-1"></i>
                        <?php echo date('d F Y, l'); ?>
                    </span>
                </p>
            </div>
            
            <!-- Floating Sidebar Toggle Button -->
            <button class="sidebar-toggle-float" onclick="toggleSidebar()" title="সাইডবার টগল করুন">
                <i class="fas fa-bars"></i>
            </button>
            
            <!-- Content Body -->
            <div class="content-body">
                <div class="container-fluid mt-4">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="card config-card">
                                <div class="card-header bg-primary text-white">
                                    <h5 class="mb-0"><i class="fas fa-cog"></i> মেসেজিং কনফিগারেশন</h5>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($success_message)): ?>
                                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                                            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST" action="">
                                        <div class="mb-4">
                                            <h5><i class="fas fa-toggle-on"></i> মেসেজিং সক্ষমকরণ</h5>
                                            
                                            <div class="form-check form-switch mb-3">
                                                <input class="form-check-input" type="checkbox" id="auto_message_enabled" name="auto_message_enabled" <?php echo $config['auto_message_enabled'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="auto_message_enabled">অটো মেসেজিং সক্ষম করুন</label>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <h5><i class="fas fa-sms"></i> মেসেজ টেমপ্লেট</h5>
                                            
                                            <label for="message_template" class="form-label">মেসেজ টেমপ্লেট:</label>
                                            <textarea class="form-control" id="message_template" name="message_template" rows="4"><?php echo htmlspecialchars($config['message_template']); ?></textarea>
                                            
                                            <div class="variable-help mt-2">
                                                <strong>ব্যবহারযোগ্য ভেরিয়েবল:</strong><br>
                                                <code>{student_name}</code> - ছাত্রের নাম<br>
                                                <code>{date}</code> - উপস্থিতির তারিখ<br>
                                                <code>{class}</code> - ক্লাসের নাম<br>
                                                <code>{roll_number}</code> - রোল নম্বর
                                            </div>
                                            
                                            <div class="message-preview mt-3">
                                                <strong>মেসেজ প্রিভিউ:</strong><br>
                                                <span id="preview_text"><?php 
                                                    $preview = $config['message_template'];
                                                    $preview = str_replace('{student_name}', 'মোহাম্মদ আলী', $preview);
                                                    $preview = str_replace('{date}', date('d/m/Y'), $preview);
                                                    $preview = str_replace('{class}', '৯ম শ্রেণি', $preview);
                                                    $preview = str_replace('{roll_number}', '১২', $preview);
                                                    echo $preview;
                                                ?></span>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-4">
                                            <h5><i class="fas fa-envelope"></i> পাঠানোর বিস্তারিত</h5>
                                            
                                            <div class="form-check form-switch mb-2">
                                                <input class="form-check-input" type="checkbox" id="send_to_guardian" name="send_to_guardian" <?php echo $config['send_to_guardian'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="send_to_guardian">অভিভাবককে মেসেজ পাঠান</label>
                                            </div>
                                            
                                            <div class="form-check form-switch mb-3">
                                                <input class="form-check-input" type="checkbox" id="send_to_student" name="send_to_student" <?php echo $config['send_to_student'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="send_to_student">ছাত্রকে মেসেজ পাঠান (যদি ফোন নম্বর থাকে)</label>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <label for="send_time_delay" class="form-label">পাঠানোর সময় বিলম্ব (মিনিটে)</label>
                                                    <input type="number" class="form-control" id="send_time_delay" name="send_time_delay" 
                                                           value="<?php echo $config['send_time_delay']; ?>" min="0" max="60">
                                                    <div class="form-text">উপস্থিতি রেকর্ডের পর কত মিনিট পর মেসেজ পাঠানো হবে</div>
                                                </div>
                                                
                                                <div class="col-md-6">
                                                    <label for="sms_gateway" class="form-label">SMS গেটওয়ে</label>
                                                    <select class="form-select" id="sms_gateway" name="sms_gateway">
                                                        <option value="non_musking" <?php echo $config['sms_gateway'] === 'non_musking' ? 'selected' : ''; ?>>Non-Musking</option>
                                                        <option value="other" <?php echo $config['sms_gateway'] === 'other' ? 'selected' : ''; ?>>অন্যান্য</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-12">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-save"></i> কনফিগারেশন সংরক্ষণ করুন
                                                </button>
                                                <a href="dashboard.php" class="btn btn-secondary ms-2">
                                                    <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div> <!-- End content-body -->
            
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
            <script src="../assets/js/script.js"></script>
            <script>
                // Update message preview when template changes
                document.getElementById('message_template').addEventListener('input', function() {
                    const template = this.value;
                    let preview = template;
                    preview = preview.replace(/{student_name}/g, 'মোহাম্মদ আলী');
                    preview = preview.replace(/{date}/g, new Date().toLocaleDateString('bn-BD'));
                    preview = preview.replace(/{class}/g, '৯ম শ্রেণি');
                    preview = preview.replace(/{roll_number}/g, '১২');
                    
                    document.getElementById('preview_text').textContent = preview;
                });
            </script>
        </div> <!-- End main-content -->
    </div> <!-- End sidebar-container -->
</body>
</html>