<?php
session_start();
require_once '../config/database.php';
require_once '../includes/site_settings.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
$site_settings = get_all_settings($pdo);
$site_name = $site_settings['site_name'] ?? 'বিদ্যা নিকেতন';

// Function to get settings from the settings table with setting_key/setting_value structure
function get_sms_settings($pdo) {
    try {
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
        $rows = $stmt->fetchAll();
        $out = [];
        foreach ($rows as $r) $out[$r['setting_key']] = $r['setting_value'];
        return $out;
    } catch (Exception $e) {
        return [];
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        
        // SMS notification settings
        $sms_notification_enabled = isset($_POST['sms_notification_enabled']) ? '1' : '0';
        $sms_send_application_confirmation = isset($_POST['sms_send_application_confirmation']) ? '1' : '0';
        $sms_send_fee_notifications = isset($_POST['sms_send_fee_notifications']) ? '1' : '0';
        $sms_send_result_notifications = isset($_POST['sms_send_result_notifications']) ? '1' : '0';
        $sms_send_bank_transaction_notifications = isset($_POST['sms_send_bank_transaction_notifications']) ? '1' : '0';
        
        // Update SMS notification settings
        $stmt->execute(['sms_notification_enabled', $sms_notification_enabled, $sms_notification_enabled]);
        $stmt->execute(['sms_send_application_confirmation', $sms_send_application_confirmation, $sms_send_application_confirmation]);
        $stmt->execute(['sms_send_fee_notifications', $sms_send_fee_notifications, $sms_send_fee_notifications]);
        $stmt->execute(['sms_send_result_notifications', $sms_send_result_notifications, $sms_send_result_notifications]);
        $stmt->execute(['sms_send_bank_transaction_notifications', $sms_send_bank_transaction_notifications, $sms_send_bank_transaction_notifications]);
        
        // Update SMS templates
        $templates = [
            'sms_tpl_application_confirmation' => $_POST['sms_tpl_application_confirmation'] ?? '',
            'sms_tpl_fee_payment' => $_POST['sms_tpl_fee_payment'] ?? '',
            'sms_tpl_fee_due_reminder' => $_POST['sms_tpl_fee_due_reminder'] ?? '',
            'sms_tpl_result_pass' => $_POST['sms_tpl_result_pass'] ?? '',
            'sms_tpl_result_fail' => $_POST['sms_tpl_result_fail'] ?? '',
            'sms_tpl_bank_transaction' => $_POST['sms_tpl_bank_transaction'] ?? '',
            'sms_tpl_bank_transaction_rejection' => $_POST['sms_tpl_bank_transaction_rejection'] ?? '',
            'non_musking_templates_general_message' => $_POST['non_musking_templates_general_message'] ?? '',
            'non_musking_templates_admission_confirmation' => $_POST['non_musking_templates_admission_confirmation'] ?? '',
            'non_musking_templates_fee_payment' => $_POST['non_musking_templates_fee_payment'] ?? '',
            'non_musking_tpl_bank_transaction' => $_POST['non_musking_templates_bank_transaction'] ?? '',
            'non_musking_tpl_bank_transaction_rejection' => $_POST['non_musking_templates_bank_transaction_rejection'] ?? ''
        ];
        
        foreach ($templates as $key => $value) {
            $stmt->execute([$key, $value, $value]);
        }
        
        $success_message = 'SMS Notification settings saved successfully!';
        
    } catch (Exception $e) {
        $error_message = 'Error: ' . $e->getMessage();
    }
}

// Load current settings
$config = get_sms_settings($pdo);
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Automated SMS Notification Settings - <?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);
        }
        
        .token-help {
            background: #e7f3ff;
            border: 1px solid #b3d7ff;
            border-radius: 8px;
            padding: 10px;
            margin-top: 5px;
            font-size: 0.875rem;
        }
    </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-bell"></i> Automated SMS Notification Settings</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> Dashboard
                    </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="">
                    <!-- SMS Notification General Settings -->
                    <h4 class="section-title"><i class="fas fa-cog"></i> General SMS Notification Settings</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_notification_enabled" name="sms_notification_enabled" 
                                       <?= ($config['sms_notification_enabled'] ?? '0') === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="sms_notification_enabled">Enable SMS Notifications</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_send_application_confirmation" name="sms_send_application_confirmation" 
                                       <?= ($config['sms_send_application_confirmation'] ?? '0') === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="sms_send_application_confirmation">Application Confirmation</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_send_fee_notifications" name="sms_send_fee_notifications" 
                                       <?= ($config['sms_send_fee_notifications'] ?? '0') === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="sms_send_fee_notifications">Fee Notifications</label>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_send_result_notifications" name="sms_send_result_notifications" 
                                       <?= ($config['sms_send_result_notifications'] ?? '0') === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="sms_send_result_notifications">Result Notifications</label>
                            </div>
                        </div>
                                
                        <div class="col-md-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="sms_send_bank_transaction_notifications" name="sms_send_bank_transaction_notifications" 
                                       <?= ($config['sms_send_bank_transaction_notifications'] ?? '0') === '1' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="sms_send_bank_transaction_notifications">Bank Transaction Notifications</label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Application Confirmation Template -->
                    <h5 class="section-title"><i class="fas fa-file-contract"></i> Application Confirmation Template</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-12">
                            <label for="sms_tpl_application_confirmation" class="form-label">Application Confirmation Message</label>
                            <textarea class="form-control" id="sms_tpl_application_confirmation" name="sms_tpl_application_confirmation" rows="3" 
                                      placeholder="Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you."><?php echo htmlspecialchars($config['sms_tpl_application_confirmation'] ?? 'Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {application_no}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Fee Notification Templates -->
                    <h5 class="section-title"><i class="fas fa-money-bill-wave"></i> Fee Notification Templates</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="sms_tpl_fee_payment" class="form-label">Fee Payment Message</label>
                            <textarea class="form-control" id="sms_tpl_fee_payment" name="sms_tpl_fee_payment" rows="3" 
                                      placeholder="Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay on time."><?php echo htmlspecialchars($config['sms_tpl_fee_payment'] ?? 'Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay on time.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {amount}, {due_date}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_fee_due_reminder" class="form-label">Fee Due Reminder Message</label>
                            <textarea class="form-control" id="sms_tpl_fee_due_reminder" name="sms_tpl_fee_due_reminder" rows="3" 
                                      placeholder="Reminder: Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay soon."><?php echo htmlspecialchars($config['sms_tpl_fee_due_reminder'] ?? 'Reminder: Dear {name}, your fee of BDT {amount} is due on {due_date}. Please pay soon.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {amount}, {due_date}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Result Notification Templates -->
                    <h5 class="section-title"><i class="fas fa-graduation-cap"></i> Result Notification Templates</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="sms_tpl_result_pass" class="form-label">Result Pass Message</label>
                            <textarea class="form-control" id="sms_tpl_result_pass" name="sms_tpl_result_pass" rows="3" 
                                      placeholder="Congratulations {name}! You have passed with grade {grade} and GPA {gpa}."><?php echo htmlspecialchars($config['sms_tpl_result_pass'] ?? 'Congratulations {name}! You have passed with grade {grade} and GPA {gpa}.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {grade}, {gpa}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="sms_tpl_result_fail" class="form-label">Result Fail Message</label>
                            <textarea class="form-control" id="sms_tpl_result_fail" name="sms_tpl_result_fail" rows="3" 
                                      placeholder="Dear {name}, you did not pass this examination. Please try again next time."><?php echo htmlspecialchars($config['sms_tpl_result_fail'] ?? 'Dear {name}, you did not pass this examination. Please try again next time.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Non-Masking Templates -->
                    <h5 class="section-title"><i class="fas fa-comment-slash"></i> Non-Masking Templates</h5>
                    
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label for="non_musking_templates_general_message" class="form-label">General Message Template</label>
                            <textarea class="form-control" id="non_musking_templates_general_message" name="non_musking_templates_general_message" rows="3" 
                                      placeholder="Dear {name}, {message}. Thank you."><?php echo htmlspecialchars($config['non_musking_templates_general_message'] ?? 'Dear {name}, {message}. Thank you.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {message}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_templates_admission_confirmation" class="form-label">Admission Confirmation Template</label>
                            <textarea class="form-control" id="non_musking_templates_admission_confirmation" name="non_musking_templates_admission_confirmation" rows="3" 
                                      placeholder="Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you."><?php echo htmlspecialchars($config['non_musking_templates_admission_confirmation'] ?? 'Dear {name}, your admission application #{application_no} has been successfully submitted. Thank you.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {application_no}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_templates_fee_payment" class="form-label">Fee Payment Template</label>
                            <textarea class="form-control" id="non_musking_templates_fee_payment" name="non_musking_templates_fee_payment" rows="3" 
                                      placeholder="Dear {name}, your fee payment of BDT {paid_amount} has been received. Current due: BDT {due_amount}. Thank you."><?php echo htmlspecialchars($config['non_musking_templates_fee_payment'] ?? 'Dear {name}, your fee payment of BDT {paid_amount} has been received. Current due: BDT {due_amount}. Thank you.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {paid_amount}, {due_amount}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_templates_bank_transaction" class="form-label">Bank Transaction Template</label>
                            <textarea class="form-control" id="non_musking_templates_bank_transaction" name="non_musking_templates_bank_transaction" rows="3" 
                                      placeholder="Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you."><?php echo htmlspecialchars($config['non_musking_tpl_bank_transaction'] ?? 'Dear {name}, your bank transaction of ৳{paid_amount} has been successfully verified. Your current due is ৳{due_amount}. Thank you.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {paid_amount}, {due_amount}
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="non_musking_templates_bank_transaction_rejection" class="form-label">Bank Transaction Rejection Template</label>
                            <textarea class="form-control" id="non_musking_templates_bank_transaction_rejection" name="non_musking_templates_bank_transaction_rejection" rows="3" 
                                      placeholder="Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration."><?php echo htmlspecialchars($config['non_musking_tpl_bank_transaction_rejection'] ?? 'Dear {name}, your bank transaction of ৳{amount} with ID {transaction_id} has been rejected. Reason: {notes}. Please contact administration.'); ?></textarea>
                            <div class="token-help">
                                <strong>Available tokens:</strong> {name}, {amount}, {transaction_id}, {notes}
                            </div>
                        </div>
                    </div>
                    
                    <!-- Submit Button -->
                    <div class="text-center">
                        <button type="submit" class="btn btn-submit me-3">
                            <i class="fas fa-save"></i> Save Settings
                        </button>
                        <a href="sms_settings.php" class="btn btn-outline-secondary">
                            <i class="fas fa-cogs"></i> SMS Service Settings
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>