<?php
session_start();
require_once '../config/database.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 {
        // MRAM portal configuration (from https://sms.mram.com.bd/Developers)
        $mram_username = 'C3002791';
        $mram_password = 'hPOWSnw8rf';
        $mram_api_key = 'C30027916974e980709412.23354057';
        $mram_sender_id = '8809601016579';
        $mram_api_url = 'https://rest.mrmessaging.net/messages';
        
        // Get form values
        $non_musking_enabled = $_POST['non_musking_enabled'] ?? '0';
        $non_musking_api_url = trim($_POST['non_musking_api_url'] ?? '');
        $non_musking_api_key = trim($_POST['non_musking_api_key'] ?? '');
        $non_musking_username = trim($_POST['non_musking_username'] ?? '');
        $non_musking_password = trim($_POST['non_musking_password'] ?? '');
        $non_musking_sender_id = trim($_POST['non_musking_sender_id'] ?? 'SCHOOL');
        
        // 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'] ?? '');
        
        // 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]);
        
        // 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]);
        
        $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);
        }
        
        .mramp-credentials {
            background: #e7f3ff;
            border: 1px solid #b3d7ff;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .sync-status {
            padding: 10px;
            border-radius: 5px;
            margin: 5px 0;
        }
        
        .sync-match {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        
        .sync-mismatch {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
    </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 সেটিংস (MRAM পোর্টালের সাথে সিঙ্ক্রোনাইজড)</h1>
                </div>
                <div class="col-md-4 text-end">
                    <a href="dashboard.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; ?>

        <!-- MRAM Portal Credentials Reference -->
        <div class="mramp-credentials">
            <h5><i class="fas fa-info-circle"></i> MRAM Developers Portal ক্রেডেনশিয়ালস (https://sms.mram.com.bd/Developers)</h5>
            <div class="row">
                <div class="col-md-6">
                    <strong>Username:</strong> C3002791<br>
                    <strong>Password:</strong> hPOWSnw8rf<br>
                </div>
                <div class="col-md-6">
                    <strong>API Key:</strong> C30027916974e980709412.23354057<br>
                    <strong>Sender ID:</strong> 8809601016579<br>
                </div>
            </div>
            <div class="mt-2">
                <strong>API URL:</strong> https://rest.mrmessaging.net/messages
            </div>
        </div>

        <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>
                            <input type="text" class="form-control" id="sms_api_key" name="sms_api_key" 
                                   value="<?php echo htmlspecialchars($sms_config['api_key'] ?? ''); ?>" 
                                   placeholder="আপনার API কী">
                        </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>
                            <input type="password" class="form-control" id="sms_password" name="sms_password" 
                                   value="<?php echo htmlspecialchars($sms_config['password'] ?? ''); ?>" 
                                   placeholder="পাসওয়ার্ড">
                        </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>
                    
                    <hr class="my-5">
                    
                    <!-- Non-Masking SMS Settings Section -->
                    <h4 class="section-title"><i class="fas fa-comment-slash"></i> নন-মাস্কিং SMS সেটিংস (MRAM পোর্টালের সাথে সিঙ্ক্রোনাইজড)</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>
                            <input type="text" class="form-control" id="non_musking_api_key" name="non_musking_api_key" 
                                   value="<?php echo htmlspecialchars($non_musking_config['api_key'] ?? ''); ?>" 
                                   placeholder="আপনার API কী">
                        </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>
                            <input type="password" class="form-control" id="non_musking_password" name="non_musking_password" 
                                   value="<?php echo htmlspecialchars($non_musking_config['password'] ?? ''); ?>" 
                                   placeholder="পাসওয়ার্ড">
                        </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 me-3">
                            <i class="fas fa-save"></i> সেটিংস সংরক্ষণ করুন
                        </button>
                        <a href="javascript:void(0)" onclick="syncWithMRAM()" class="btn btn-outline-primary">
                            <i class="fas fa-sync-alt"></i> MRAM পোর্টালের সাথে সিঙ্ক করুন
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function syncWithMRAM() {
            // Fill in the MRAM credentials
            document.getElementById('non_musking_api_url').value = 'https://rest.mrmessaging.net/messages';
            document.getElementById('non_musking_api_key').value = 'C30027916974e980709412.23354057';
            document.getElementById('non_musking_username').value = 'C3002791';
            document.getElementById('non_musking_password').value = 'hPOWSnw8rf';
            document.getElementById('non_musking_sender_id').value = '8809601016579';
            
            // Also sync general SMS settings
            document.getElementById('sms_api_url').value = 'https://rest.mrmessaging.net/messages';
            document.getElementById('sms_api_key').value = 'C30027916974e980709412.23354057';
            document.getElementById('sms_username').value = 'C3002791';
            document.getElementById('sms_password').value = 'hPOWSnw8rf';
            document.getElementById('sms_sender_id').value = '8809601016579';
            
            // Enable non-masking
            document.getElementById('non_musking_enabled').value = '1';
            
            alert('MRAM পোর্টালের ক্রেডেনশিয়ালস সিঙ্ক্রোনাইজড!');
        }
    </script>
</body>
</html>