<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Email & SMS Settings
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';
require_once dirname(__DIR__, 2) . '/config/mailer.php';

// Require authentication and permission
require_auth();
require_permission('settings.edit');

// Set page title
$page_title = 'Email & SMS Settings';

// Get current user
$current_user = current_user();

// Handle form submissions
$message = '';
$error = '';

// Email Configuration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email_config'])) {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        // Update email settings in database
        $settings = [
            'smtp_host' => sanitize_input($_POST['smtp_host'] ?? ''),
            'smtp_port' => (int)($_POST['smtp_port'] ?? 587),
            'smtp_user' => sanitize_input($_POST['smtp_user'] ?? ''),
            'smtp_pass' => $_POST['smtp_pass'] ?? '',
            'smtp_encryption' => sanitize_input($_POST['smtp_encryption'] ?? 'tls'),
            'smtp_from_email' => sanitize_input($_POST['smtp_from_email'] ?? ''),
            'smtp_from_name' => sanitize_input($_POST['smtp_from_name'] ?? ''),
            'email_enabled' => isset($_POST['email_enabled']) ? 1 : 0
        ];
        
        // Don't update password if empty (keep existing)
        if (empty($settings['smtp_pass'])) {
            unset($settings['smtp_pass']);
        }
        
        try {
            foreach ($settings as $key => $value) {
                save_setting($key, $value);
            }
            $message = 'Email configuration updated successfully';
            audit_log($current_user['user_id'], AUDIT_UPDATE, 'system_settings', null, null, $settings);
        } catch (Exception $e) {
            $error = 'Failed to update email settings: ' . $e->getMessage();
        }
    }
}

// SMS Configuration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sms_config'])) {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $settings = [
            'sms_provider' => sanitize_input($_POST['sms_provider'] ?? ''),
            'sms_api_key' => sanitize_input($_POST['sms_api_key'] ?? ''),
            'sms_api_secret' => $_POST['sms_api_secret'] ?? '',
            'sms_sender_id' => sanitize_input($_POST['sms_sender_id'] ?? ''),
            'sms_enabled' => isset($_POST['sms_enabled']) ? 1 : 0
        ];
        
        // Don't update secret if empty
        if (empty($settings['sms_api_secret'])) {
            unset($settings['sms_api_secret']);
        }
        
        try {
            foreach ($settings as $key => $value) {
                save_setting($key, $value);
            }
            $message = 'SMS configuration updated successfully';
            audit_log($current_user['user_id'], AUDIT_UPDATE, 'system_settings', null, null, $settings);
        } catch (Exception $e) {
            $error = 'Failed to update SMS settings: ' . $e->getMessage();
        }
    }
}

// Email Template CRUD
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['template_action'])) {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['template_action'];
        
        switch ($action) {
            case 'create_template':
                $template_code = sanitize_input($_POST['template_code'] ?? '');
                $template_name = sanitize_input($_POST['template_name'] ?? '');
                $template_type = sanitize_input($_POST['template_type'] ?? 'email');
                $subject = sanitize_input($_POST['subject'] ?? '');
                $body = $_POST['body'] ?? '';
                $variables = sanitize_input($_POST['variables'] ?? '');
                
                if (empty($template_code)) {
                    $error = 'Template code is required';
                } elseif (empty($template_name)) {
                    $error = 'Template name is required';
                } elseif (empty($subject)) {
                    $error = 'Subject is required';
                } elseif (empty($body)) {
                    $error = 'Body is required';
                } else {
                    // Check if code exists
                    $exists = db_fetch_value("SELECT COUNT(*) FROM notification_templates WHERE template_code = ?", [$template_code]);
                    if ($exists) {
                        $error = 'Template code already exists';
                    } else {
                        try {
                            db_insert('notification_templates', [
                                'template_code' => $template_code,
                                'template_name' => $template_name,
                                'template_type' => $template_type,
                                'subject' => $subject,
                                'body' => $body,
                                'variables' => $variables,
                                'is_active' => 1
                            ]);
                            $message = 'Template created successfully';
                            audit_log($current_user['user_id'], AUDIT_CREATE, 'notification_templates', null, null, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to create template: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'edit_template':
                $template_id = (int)($_POST['template_id'] ?? 0);
                $template_code = sanitize_input($_POST['template_code'] ?? '');
                $template_name = sanitize_input($_POST['template_name'] ?? '');
                $template_type = sanitize_input($_POST['template_type'] ?? 'email');
                $subject = sanitize_input($_POST['subject'] ?? '');
                $body = $_POST['body'] ?? '';
                $variables = sanitize_input($_POST['variables'] ?? '');
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!$template_id) {
                    $error = 'Invalid template ID';
                } elseif (empty($template_code)) {
                    $error = 'Template code is required';
                } elseif (empty($template_name)) {
                    $error = 'Template name is required';
                } elseif (empty($subject)) {
                    $error = 'Subject is required';
                } elseif (empty($body)) {
                    $error = 'Body is required';
                } else {
                    // Check if code exists for another template
                    $exists = db_fetch_value("SELECT COUNT(*) FROM notification_templates WHERE template_code = ? AND template_id != ?", 
                                            [$template_code, $template_id]);
                    if ($exists) {
                        $error = 'Template code already exists';
                    } else {
                        try {
                            $old = db_fetch_one("SELECT * FROM notification_templates WHERE template_id = ?", [$template_id]);
                            db_update('notification_templates', [
                                'template_code' => $template_code,
                                'template_name' => $template_name,
                                'template_type' => $template_type,
                                'subject' => $subject,
                                'body' => $body,
                                'variables' => $variables,
                                'is_active' => $is_active
                            ], 'template_id = ?', [$template_id]);
                            $message = 'Template updated successfully';
                            audit_log($current_user['user_id'], AUDIT_UPDATE, 'notification_templates', $template_id, $old, $_POST);
                        } catch (Exception $e) {
                            $error = 'Failed to update template: ' . $e->getMessage();
                        }
                    }
                }
                break;
                
            case 'delete_template':
                $template_id = (int)($_POST['template_id'] ?? 0);
                
                if (!$template_id) {
                    $error = 'Invalid template ID';
                } else {
                    try {
                        db_delete('notification_templates', 'template_id = ?', [$template_id]);
                        $message = 'Template deleted successfully';
                        audit_log($current_user['user_id'], AUDIT_DELETE, 'notification_templates', $template_id);
                    } catch (Exception $e) {
                        $error = 'Failed to delete template: ' . $e->getMessage();
                    }
                }
                break;
        }
    }
}

// Test Email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_email'])) {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $test_email = sanitize_input($_POST['test_email_address'] ?? '');
        
        if (empty($test_email)) {
            $error = 'Please enter an email address';
        } elseif (!validate_email($test_email)) {
            $error = 'Invalid email address';
        } else {
            $result = test_email_configuration($test_email);
            if ($result === true) {
                $message = 'Test email sent successfully to ' . $test_email;
            } else {
                $error = $result;
            }
        }
    }
}

// Get all settings
$email_settings = [
    'smtp_host' => get_setting('smtp_host', SMTP_HOST),
    'smtp_port' => get_setting('smtp_port', SMTP_PORT),
    'smtp_user' => get_setting('smtp_user', SMTP_USER),
    'smtp_encryption' => get_setting('smtp_encryption', SMTP_ENCRYPTION),
    'smtp_from_email' => get_setting('smtp_from_email', SMTP_FROM_EMAIL),
    'smtp_from_name' => get_setting('smtp_from_name', SMTP_FROM_NAME),
    'email_enabled' => get_setting('email_enabled', ENABLE_EMAIL)
];

$sms_settings = [
    'sms_provider' => get_setting('sms_provider', ''),
    'sms_api_key' => get_setting('sms_api_key', ''),
    'sms_sender_id' => get_setting('sms_sender_id', 'RUHONDO'),
    'sms_enabled' => get_setting('sms_enabled', ENABLE_SMS)
];

// Get all templates
$templates = db_fetch_all("
    SELECT * FROM notification_templates 
    ORDER BY template_type, template_name
");

// Get template to edit
$edit_template = null;
if (isset($_GET['edit_template'])) {
    $edit_template = db_fetch_one("SELECT * FROM notification_templates WHERE template_id = ?", [(int)$_GET['edit_template']]);
}

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.php';
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Email & SMS Settings</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/settings/index.php'); ?>">Settings</a></li>
                    <li class="breadcrumb-item active">Email & SMS</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-6">
                <!-- Email Configuration -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-envelope mr-1"></i>
                            Email Configuration
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="email_config" value="1">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="email_enabled" name="email_enabled"
                                           <?php echo $email_settings['email_enabled'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="email_enabled">Enable Email Notifications</label>
                                </div>
                            </div>
                            
                            <hr>
                            
                            <h5>SMTP Settings</h5>
                            
                            <div class="form-group">
                                <label for="smtp_host">SMTP Host</label>
                                <input type="text" class="form-control" id="smtp_host" name="smtp_host" 
                                       value="<?php echo escape_html($email_settings['smtp_host']); ?>"
                                       placeholder="e.g., smtp.gmail.com">
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="smtp_port">SMTP Port</label>
                                        <input type="number" class="form-control" id="smtp_port" name="smtp_port" 
                                               value="<?php echo $email_settings['smtp_port']; ?>"
                                               placeholder="587">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="smtp_encryption">Encryption</label>
                                        <select class="form-control" id="smtp_encryption" name="smtp_encryption">
                                            <option value="tls" <?php echo $email_settings['smtp_encryption'] == 'tls' ? 'selected' : ''; ?>>TLS</option>
                                            <option value="ssl" <?php echo $email_settings['smtp_encryption'] == 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                            <option value="" <?php echo empty($email_settings['smtp_encryption']) ? 'selected' : ''; ?>>None</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="smtp_user">SMTP Username</label>
                                <input type="text" class="form-control" id="smtp_user" name="smtp_user" 
                                       value="<?php echo escape_html($email_settings['smtp_user']); ?>"
                                       placeholder="your-email@example.com">
                            </div>
                            
                            <div class="form-group">
                                <label for="smtp_pass">SMTP Password</label>
                                <input type="password" class="form-control" id="smtp_pass" name="smtp_pass" 
                                       placeholder="Leave empty to keep current password">
                                <small class="text-muted">Leave empty to keep current password</small>
                            </div>
                            
                            <hr>
                            
                            <h5>Default From Address</h5>
                            
                            <div class="form-group">
                                <label for="smtp_from_email">From Email</label>
                                <input type="email" class="form-control" id="smtp_from_email" name="smtp_from_email" 
                                       value="<?php echo escape_html($email_settings['smtp_from_email']); ?>"
                                       placeholder="noreply@ruhondo.com">
                            </div>
                            
                            <div class="form-group">
                                <label for="smtp_from_name">From Name</label>
                                <input type="text" class="form-control" id="smtp_from_name" name="smtp_from_name" 
                                       value="<?php echo escape_html($email_settings['smtp_from_name']); ?>"
                                       placeholder="Ruhondo Beach Resort">
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save mr-1"></i> Save Email Settings
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Test Email -->
                <div class="card mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-paper-plane mr-1"></i>
                            Test Email Configuration
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="test_email" value="1">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="test_email_address">Send Test Email To</label>
                                <div class="input-group">
                                    <input type="email" class="form-control" id="test_email_address" name="test_email_address" 
                                           placeholder="Enter email address" required>
                                    <div class="input-group-append">
                                        <button type="submit" class="btn btn-success">
                                            <i class="fas fa-paper-plane mr-1"></i> Send Test
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-md-6">
                <!-- SMS Configuration -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-mobile-alt mr-1"></i>
                            SMS Configuration
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="sms_config" value="1">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="sms_enabled" name="sms_enabled"
                                           <?php echo $sms_settings['sms_enabled'] ? 'checked' : ''; ?>>
                                    <label class="custom-control-label" for="sms_enabled">Enable SMS Notifications</label>
                                </div>
                            </div>
                            
                            <hr>
                            
                            <div class="form-group">
                                <label for="sms_provider">SMS Provider</label>
                                <select class="form-control" id="sms_provider" name="sms_provider">
                                    <option value="">Select Provider</option>
                                    <option value="twilio" <?php echo $sms_settings['sms_provider'] == 'twilio' ? 'selected' : ''; ?>>Twilio</option>
                                    <option value="africastalking" <?php echo $sms_settings['sms_provider'] == 'africastalking' ? 'selected' : ''; ?>>Africa's Talking</option>
                                    <option value="infobip" <?php echo $sms_settings['sms_provider'] == 'infobip' ? 'selected' : ''; ?>>Infobip</option>
                                    <option value="custom" <?php echo $sms_settings['sms_provider'] == 'custom' ? 'selected' : ''; ?>>Custom API</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="sms_api_key">API Key</label>
                                <input type="text" class="form-control" id="sms_api_key" name="sms_api_key" 
                                       value="<?php echo escape_html($sms_settings['sms_api_key']); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label for="sms_api_secret">API Secret</label>
                                <input type="password" class="form-control" id="sms_api_secret" name="sms_api_secret" 
                                       placeholder="Leave empty to keep current">
                            </div>
                            
                            <div class="form-group">
                                <label for="sms_sender_id">Sender ID</label>
                                <input type="text" class="form-control" id="sms_sender_id" name="sms_sender_id" 
                                       value="<?php echo escape_html($sms_settings['sms_sender_id']); ?>"
                                       placeholder="RUHONDO">
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Note:</strong> SMS functionality requires additional configuration with your chosen provider.
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save mr-1"></i> Save SMS Settings
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Email Templates -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-alt mr-1"></i>
                            Notification Templates
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#createTemplateModal">
                                <i class="fas fa-plus"></i> New Template
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Code</th>
                                        <th>Name</th>
                                        <th>Type</th>
                                        <th>Subject</th>
                                        <th>Variables</th>
                                        <th>Status</th>
                                        <th width="100">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($templates as $template): ?>
                                    <tr>
                                        <td><strong><?php echo escape_html($template['template_code']); ?></strong></td>
                                        <td><?php echo escape_html($template['template_name']); ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo $template['template_type'] == 'email' ? 'info' : 'success'; ?>">
                                                <?php echo strtoupper($template['template_type']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo escape_html($template['subject']); ?></td>
                                        <td>
                                            <?php if ($template['variables']): ?>
                                                <span class="badge badge-secondary"><?php echo escape_html($template['variables']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($template['is_active']): ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-danger">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <a href="?edit_template=<?php echo $template['template_id']; ?>" class="btn btn-sm btn-warning">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-danger" 
                                                    onclick="deleteTemplate(<?php echo $template['template_id']; ?>, '<?php echo escape_html($template['template_name']); ?>')">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Edit Template Form -->
        <?php if ($edit_template): ?>
        <div class="row">
            <div class="col-12">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit Template: <?php echo escape_html($edit_template['template_code']); ?>
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="template_action" value="edit_template">
                        <input type="hidden" name="template_id" value="<?php echo $edit_template['template_id']; ?>">
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_template_code">Template Code <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_template_code" name="template_code" 
                                               value="<?php echo escape_html($edit_template['template_code']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="edit_template_name">Template Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_template_name" name="template_name" 
                                               value="<?php echo escape_html($edit_template['template_name']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="edit_template_type">Type</label>
                                        <select class="form-control" id="edit_template_type" name="template_type">
                                            <option value="email" <?php echo $edit_template['template_type'] == 'email' ? 'selected' : ''; ?>>Email</option>
                                            <option value="sms" <?php echo $edit_template['template_type'] == 'sms' ? 'selected' : ''; ?>>SMS</option>
                                        </select>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="edit_subject">Subject <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="edit_subject" name="subject" 
                                               value="<?php echo escape_html($edit_template['subject']); ?>" required>
                                    </div>
                                    
                                    <div class="form-group">
                                        <label for="edit_variables">Available Variables</label>
                                        <input type="text" class="form-control" id="edit_variables" name="variables" 
                                               value="<?php echo escape_html($edit_template['variables']); ?>"
                                               placeholder="e.g., guest_name, booking_code">
                                        <small class="text-muted">Comma separated list of variable names (without braces)</small>
                                    </div>
                                    
                                    <div class="form-group">
                                        <div class="custom-control custom-switch">
                                            <input type="checkbox" class="custom-control-input" id="edit_is_active" name="is_active"
                                                   <?php echo $edit_template['is_active'] ? 'checked' : ''; ?>>
                                            <label class="custom-control-label" for="edit_is_active">Active</label>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="edit_body">Template Body <span class="text-danger">*</span></label>
                                        <textarea class="form-control" id="edit_body" name="body" rows="15" required><?php echo escape_html($edit_template['body']); ?></textarea>
                                        <small class="text-muted">
                                            Use {variable_name} syntax for placeholders. For SMS, keep it short.
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save mr-1"></i> Update Template
                            </button>
                            <a href="?" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Create Template Modal -->
<div class="modal fade" id="createTemplateModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary">
                <h5 class="modal-title">Create Notification Template</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            
            <form method="POST">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="template_action" value="create_template">
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="template_code">Template Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="template_code" name="template_code" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="template_name">Template Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="template_name" name="template_name" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="template_type">Type</label>
                                <select class="form-control" id="template_type" name="template_type">
                                    <option value="email">Email</option>
                                    <option value="sms">SMS</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="subject">Subject <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="subject" name="subject" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="variables">Available Variables</label>
                                <input type="text" class="form-control" id="variables" name="variables" 
                                       placeholder="guest_name, booking_code, check_in">
                                <small class="text-muted">Comma separated list</small>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="body">Template Body <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="body" name="body" rows="10" required></textarea>
                                <small class="text-muted">Use {variable_name} syntax for placeholders</small>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Template Modal -->
<div class="modal fade" id="deleteTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Template</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete template <strong id="deleteTemplateName"></strong>?</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteTemplateForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="template_action" value="delete_template">
                    <input type="hidden" name="template_id" id="deleteTemplateId">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function deleteTemplate(templateId, templateName) {
    $('#deleteTemplateId').val(templateId);
    $('#deleteTemplateName').text(templateName);
    $('#deleteTemplateModal').modal('show');
}

// Preview template variables (simple)
$('#edit_body, #body').on('input', function() {
    // Could add live preview here
});
</script>

<?php
// Helper function to save settings
function save_setting($key, $value) {
    $exists = db_fetch_value("SELECT COUNT(*) FROM system_settings WHERE setting_key = ?", [$key]);
    
    if ($exists) {
        db_update('system_settings', ['setting_value' => $value, 'updated_by' => current_user_id()], 'setting_key = ?', [$key]);
    } else {
        db_insert('system_settings', [
            'setting_key' => $key,
            'setting_value' => $value,
            'setting_type' => 'text',
            'updated_by' => current_user_id()
        ]);
    }
}

// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>