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

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

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Non-masking SMS settings
        $non_musking_enabled = $_POST['non_musking_enabled'] ?? '0';
        $non_musking_api_url = $_POST['non_musking_api_url'] ?? '';
        $non_musking_api_key = $_POST['non_musking_api_key'] ?? '';
        $non_musking_username = $_POST['non_musking_username'] ?? '';
        $non_musking_password = $_POST['non_musking_password'] ?? '';
        $non_musking_sender_id = $_POST['non_musking_sender_id'] ?? 'SCHOOL';
        $non_musking_general_template = $_POST['non_musking_general_template'] ?? 'প্রিয় {name}, {message}. ধন্যবাদ।';
        $non_musking_admission_template = $_POST['non_musking_admission_template'] ?? 'প্রিয় {name}, আপনার ভর্তি আবেদন সফলভাবে জমা দেওয়া হয়েছে। আবেদন নম্বর: {application_no}। ধন্যবাদ।';
        
        // General SMS settings
        $sms_enabled = isset($_POST['sms_enabled']) ? '1' : '0';
        $sms_test_mode = isset($_POST['sms_test_mode']) ? '1' : '0';
        $sms_send_to_guardian = isset($_POST['sms_send_to_guardian']) ? '1' : '0';
        $sms_api_url = trim($_POST['sms_api_url'] ?? '');
        $sms_api_key = trim($_POST['sms_api_key'] ?? '');
        $sms_username = trim($_POST['sms_username'] ?? '');
        $sms_password = trim($_POST['sms_password'] ?? '');
        $sms_sender_id = trim($_POST['sms_sender_id'] ?? '');
        $sms_tpl_admission_success = trim($_POST['sms_tpl_admission_success'] ?? '');
        $sms_tpl_result_pass = trim($_POST['sms_tpl_result_pass'] ?? '');
        $sms_tpl_result_fail = trim($_POST['sms_tpl_result_fail'] ?? '');
        $sms_tpl_fee_payment = trim($_POST['sms_tpl_fee_payment'] ?? '');
        $sms_tpl_fee_due_reminder = trim($_POST['sms_tpl_fee_due_reminder'] ?? '');
        $sms_tpl_bill_submission = trim($_POST['sms_tpl_bill_submission'] ?? '');
        
        // Update settings in database
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        
        // Update non-masking settings
        $stmt->execute(['non_musking_enabled', $non_musking_enabled, $non_musking_enabled]);
        $stmt->execute(['non_musking_api_url', $non_musking_api_url, $non_musking_api_url]);
        $stmt->execute(['non_musking_api_key', $non_musking_api_key, $non_musking_api_key]);
        $stmt->execute(['non_musking_username', $non_musking_username, $non_musking_username]);
        $stmt->execute(['non_musking_password', $non_musking_password, $non_musking_password]);
        $stmt->execute(['non_musking_sender_id', $non_musking_sender_id, $non_musking_sender_id]);
        $stmt->execute(['non_musking_tpl_general_message', $non_musking_general_template, $non_musking_general_template]);
        $stmt->execute(['non_musking_tpl_admission_confirmation', $non_musking_admission_template, $non_musking_admission_template]);
        
        // Update general SMS settings
        $stmt->execute(['sms_enabled', $sms_enabled, $sms_enabled]);
        $stmt->execute(['sms_test_mode', $sms_test_mode, $sms_test_mode]);
        $stmt->execute(['sms_send_to_guardian', $sms_send_to_guardian, $sms_send_to_guardian]);
        $stmt->execute(['sms_api_url', $sms_api_url, $sms_api_url]);
        $stmt->execute(['sms_api_key', $sms_api_key, $sms_api_key]);
        $stmt->execute(['sms_username', $sms_username, $sms_username]);
        $stmt->execute(['sms_password', $sms_password, $sms_password]);
        $stmt->execute(['sms_sender_id', $sms_sender_id, $sms_sender_id]);
        $stmt->execute(['sms_tpl_admission_success', $sms_tpl_admission_success, $sms_tpl_admission_success]);
        $stmt->execute(['sms_tpl_result_pass', $sms_tpl_result_pass, $sms_tpl_result_pass]);
        $stmt->execute(['sms_tpl_result_fail', $sms_tpl_result_fail, $sms_tpl_result_fail]);
        $stmt->execute(['sms_tpl_fee_payment', $sms_tpl_fee_payment, $sms_tpl_fee_payment]);
        $stmt->execute(['sms_tpl_fee_due_reminder', $sms_tpl_fee_due_reminder, $sms_tpl_fee_due_reminder]);
        $stmt->execute(['sms_tpl_bill_submission', $sms_tpl_bill_submission, $sms_tpl_bill_submission]);
        
        $success_message = 'SMS সেটিংস সফলভাবে সংরক্ষিত হয়েছে!';
        
    } catch (Exception $e) {
        $error_message = 'ত্রুটি: ' . $e->getMessage();
    }
}

// Load current settings
$non_musking_config = non_musking_config();
$sms_config = sms_config();
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMS সেটিংস - <?php echo htmlspecialchars($site_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="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif;
            background: #f5f7fa; 
        }
        
        .admin-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: #fff;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            border-bottom: 3px solid #F42A41;
        }
        
        .settings-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,103,71,0.15);
            border: 1px solid #e0e0e0;
            margin-bottom: 2rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #006747;
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
            font-weight: 600;
            padding: 12px 30px;
        }
        
        .btn-submit:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 103, 71, 0.4);
        }
        
        .section-title {
            color: #006747;
            border-bottom: 2px solid #F42A41;
            padding-bottom: 10px;
            margin-bottom: 20px;
            font-weight: 700;
        }
        
        .form-control:focus,
        .form-select:focus {
            border-color: #006747;
            box-shadow: 0 0 0 0.25rem rgba(0, 103, 71, 0.15);
        }
        
        .section-divider {
            height: 1px;
            background: linear-gradient(to right, transparent, #ddd, transparent);
            margin: 30px 0;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="admin-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-comment-alt"></i> SMS সেটিংস</h1>
                </div>
                <div class="col-md-4 text-end">
                    <a href="index.php" class="btn btn-outline-light">
                        <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?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; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="settings-card">
            <div class="card-body p-4">
                <form method="POST" action="">
                    <!-- General SMS Settings Section -->
                    <h4 class="section-title"><i class="fas fa-cogs"></i> জেনারেল SMS সেটিংস</h4>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_enabled" name="sms_enabled" <?= ($sms_config['enabled'] ?? false) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="sms_enabled">SMS সক্রিয় করুন</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_test_mode" name="sms_test_mode" <?= ($sms_config['test_mode'] ?? true) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="sms_test_mode">টেস্ট মোড</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_send_to_guardian" name="sms_send_to_guardian" <?= ($sms_config['send_to_guardian_also'] ?? true) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="sms_send_to_guardian">অভিভাবকেও পাঠান</label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="sms_api_url" class="form-label">API URL</label>
                            <input type="text" class="form-control" id="sms_api_url" name="sms_api_url" 
                                   value="<?php echo htmlspecialchars($sms_config['api_url'] ?? ''); ?>" 
                                   placeholder="https://api.smsprovider.com/send">
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_sender_id" class="form-label">সেন্ডার ID</label>
                            <input type="text" class="form-control" id="sms_sender_id" name="sms_sender_id" 
                                   value="<?php echo htmlspecialchars($sms_config['sender_id'] ?? ''); ?>" 
                                   placeholder="SCHOOL বা আপনার ইচ্ছামত টেক্সট">
                        </div>
                        
                        <div class="col-md-4">
                            <label for="sms_api_key" class="form-label">API কী</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="sms_api_key" name="sms_api_key" 
                                       value="<?php echo htmlspecialchars($sms_config['api_key'] ?? ''); ?>" 
                                       placeholder="আপনার API কী">
                                <button class="btn btn-outline-secondary" type="button" id="toggle_sms_api_key">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <label for="sms_username" class="form-label">ব্যবহারকারীর নাম</label>
                            <input type="text" class="form-control" id="sms_username" name="sms_username" 
                                   value="<?php echo htmlspecialchars($sms_config['username'] ?? ''); ?>" 
                                   placeholder="ব্যবহারকারীর নাম">
                        </div>
                        
                        <div class="col-md-4">
                            <label for="sms_password" class="form-label">পাসওয়ার্ড</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="sms_password" name="sms_password" 
                                       value="<?php echo htmlspecialchars($sms_config['password'] ?? ''); ?>" 
                                       placeholder="পাসওয়ার্ড">
                                <button class="btn btn-outline-secondary" type="button" id="toggle_sms_password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- General Templates Section -->
                    <h5 class="section-title"><i class="fas fa-envelope-open-text"></i> জেনারেল টেমপ্লেটস</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-12">
                            <label for="sms_tpl_admission_success" class="form-label">ভর্তি সফলতার টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_admission_success" name="sms_tpl_admission_success" rows="2" 
                                      placeholder="আপনার ভর্তি সফল হয়েছে..."><?php echo htmlspecialchars($sms_config['templates']['admission_success'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_result_pass" class="form-label">রেজাল্ট (পাস) টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_result_pass" name="sms_tpl_result_pass" rows="2" 
                                      placeholder="আপনি পাস করেছেন..."><?php echo htmlspecialchars($sms_config['templates']['result_pass'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_result_fail" class="form-label">রেজাল্ট (ফেল) টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_result_fail" name="sms_tpl_result_fail" rows="2" 
                                      placeholder="আপনি ফেল করেছেন..."><?php echo htmlspecialchars($sms_config['templates']['result_fail'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_fee_payment" class="form-label">ফি পেমেন্ট টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_fee_payment" name="sms_tpl_fee_payment" rows="2" 
                                      placeholder="আপনার ফি পেমেন্ট হয়েছে..."><?php echo htmlspecialchars($sms_config['templates']['fee_payment'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_fee_due_reminder" class="form-label">ফি বাকি রিমাইন্ডার টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_fee_due_reminder" name="sms_tpl_fee_due_reminder" rows="2" 
                                      placeholder="আপনার ফি বাকি রয়েছে..."><?php echo htmlspecialchars($sms_config['templates']['fee_due_reminder'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="col-md-12">
                            <label for="sms_tpl_bill_submission" class="form-label">বিল সাবমিশন টেমপ্লেট</label>
                            <textarea class="form-control" id="sms_tpl_bill_submission" name="sms_tpl_bill_submission" rows="2" 
                                      placeholder="আপনার বিল জমা হয়েছে..."><?php echo htmlspecialchars($sms_config['templates']['bill_submission'] ?? ''); ?></textarea>
                        </div>
                    </div>
                    
                    <div class="section-divider"></div>
                    
                    <!-- Non-Masking SMS Settings Section -->
                    <h4 class="section-title"><i class="fas fa-comment-slash"></i> নন-মাস্কিং SMS সেটিংস</h4>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="non_musking_enabled" class="form-label">নন-মাস্কিং সক্রিয় করুন</label>
                            <select class="form-select" id="non_musking_enabled" name="non_musking_enabled">
                                <option value="0" <?php echo !($non_musking_config['enabled'] ?? false) ? 'selected' : ''; ?>>নিষ্ক্রিয়</option>
                                <option value="1" <?php echo ($non_musking_config['enabled'] ?? false) ? 'selected' : ''; ?>>সক্রিয়</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_sender_id" class="form-label">সেন্ডার ID</label>
                            <input type="text" class="form-control" id="non_musking_sender_id" name="non_musking_sender_id" 
                                   value="<?php echo htmlspecialchars($non_musking_config['sender_id'] ?? 'SCHOOL'); ?>" 
                                   placeholder="SCHOOL বা আপনার ইচ্ছামত টেক্সট">
                        </div>
                    </div>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-12">
                            <label for="non_musking_api_url" class="form-label">API URL</label>
                            <input type="url" class="form-control" id="non_musking_api_url" name="non_musking_api_url" 
                                   value="<?php echo htmlspecialchars($non_musking_config['api_url'] ?? ''); ?>" 
                                   placeholder="https://api.smsprovider.com/send">
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_api_key" class="form-label">API কী</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="non_musking_api_key" name="non_musking_api_key" 
                                       value="<?php echo htmlspecialchars($non_musking_config['api_key'] ?? ''); ?>" 
                                       placeholder="আপনার API কী">
                                <button class="btn btn-outline-secondary" type="button" id="toggle_non_musking_api_key">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_username" class="form-label">ব্যবহারকারীর নাম</label>
                            <input type="text" class="form-control" id="non_musking_username" name="non_musking_username" 
                                   value="<?php echo htmlspecialchars($non_musking_config['username'] ?? ''); ?>" 
                                   placeholder="ব্যবহারকারীর নাম">
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_password" class="form-label">পাসওয়ার্ড</label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="non_musking_password" name="non_musking_password" 
                                       value="<?php echo htmlspecialchars($non_musking_config['password'] ?? ''); ?>" 
                                       placeholder="পাসওয়ার্ড">
                                <button class="btn btn-outline-secondary" type="button" id="toggle_non_musking_password">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Non-Masking Templates Section -->
                    <h5 class="section-title"><i class="fas fa-envelope"></i> নন-মাস্কিং টেমপ্লেটস</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-12">
                            <label for="non_musking_general_template" class="form-label">সাধারণ বার্তার টেমপ্লেট</label>
                            <textarea class="form-control" id="non_musking_general_template" name="non_musking_general_template" rows="3" 
                                      placeholder="প্রিয় {name}, {message}. ধন্যবাদ।"><?php echo htmlspecialchars($non_musking_config['templates']['general_message'] ?? 'প্রিয় {name}, {message}. ধন্যবাদ।'); ?></textarea>
                            <div class="form-text">ব্যবহারযোগ্য টোকেন: {name}, {message}</div>
                        </div>
                        
                        <div class="col-md-12">
                            <label for="non_musking_admission_template" class="form-label">ভর্তি নিশ্চিতকরণ টেমপ্লেট</label>
                            <textarea class="form-control" id="non_musking_admission_template" name="non_musking_admission_template" rows="3" 
                                      placeholder="প্রিয় {name}, আপনার ভর্তি আবেদন সফলভাবে জমা দেওয়া হয়েছে। আবেদন নম্বর: {application_no}। ধন্যবাদ।"><?php echo htmlspecialchars($non_musking_config['templates']['admission_confirmation'] ?? 'প্রিয় {name}, আপনার ভর্তি আবেদন সফলভাবে জমা দেওয়া হয়েছে। আবেদন নম্বর: {application_no}। ধন্যবাদ।'); ?></textarea>
                            <div class="form-text">ব্যবহারযোগ্য টোকেন: {name}, {application_no}</div>
                        </div>
                    </div>
                    
                    <!-- Submit Button -->
                    <div class="text-center">
                        <button type="submit" class="btn btn-submit">
                            <i class="fas fa-save"></i> সেটিংস সংরক্ষণ করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle API key visibility
        document.getElementById('toggle_sms_api_key').addEventListener('click', function() {
            const apiKeyInput = document.getElementById('sms_api_key');
            const icon = this.querySelector('i');
            
            if (apiKeyInput.type === 'password') {
                apiKeyInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                apiKeyInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
        
        document.getElementById('toggle_non_musking_api_key').addEventListener('click', function() {
            const apiKeyInput = document.getElementById('non_musking_api_key');
            const icon = this.querySelector('i');
            
            if (apiKeyInput.type === 'password') {
                apiKeyInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                apiKeyInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
        
        document.getElementById('toggle_sms_password').addEventListener('click', function() {
            const passwordInput = document.getElementById('sms_password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
        
        document.getElementById('toggle_non_musking_password').addEventListener('click', function() {
            const passwordInput = document.getElementById('non_musking_password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    </script>
</body>
</html>