<?php
require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login with settings permission
$auth = new AdminAuth();
$auth->requireLogin();
$auth->requirePermission('settings', 'edit');

// Set JSON response header
header('Content-Type: application/json');

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['template_type']) || !isset($input['html_content'])) {
        throw new Exception('Invalid input data');
    }
    
    $templateType = $input['template_type'];
    $htmlContent = $input['html_content'];
    
    // Validate template type
    $validTemplates = [
        'pending_registration',
        'registration_confirmation', 
        'payment_failure',
        'payment_reminder_24h',
        'payment_reminder_48h',
        'payment_reminder_7d',
        'admin_notification'
    ];
    
    if (!in_array($templateType, $validTemplates)) {
        throw new Exception('Invalid template type');
    }
    
    // Save to database
    $pdo = getDBConnection();
    $settingKey = 'emailTemplate_' . $templateType . '_html';
    
    // Check if setting exists
    $stmt = $pdo->prepare("SELECT id FROM admin_settings WHERE setting_key = ?");
    $stmt->execute([$settingKey]);
    
    if ($stmt->fetch()) {
        // Update existing
        $stmt = $pdo->prepare("UPDATE admin_settings SET setting_value = ?, updated_at = CURRENT_TIMESTAMP, updated_by = ? WHERE setting_key = ?");
        $stmt->execute([$htmlContent, $_SESSION['admin_user']['username'] ?? 'system', $settingKey]);
    } else {
        // Insert new
        $stmt = $pdo->prepare("INSERT INTO admin_settings (setting_key, setting_value, setting_type, description, updated_by) VALUES (?, ?, 'template', ?, ?)");
        $description = "Custom HTML template for " . str_replace('_', ' ', $templateType);
        $stmt->execute([$settingKey, $htmlContent, $description, $_SESSION['admin_user']['username'] ?? 'system']);
    }
    
    // Log the activity
    if (class_exists('AdminActivityLogger')) {
        $logger = new AdminActivityLogger();
        $logger->log('template_update', 'email_template', null, "Updated HTML template: $templateType");
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Template saved successfully'
    ]);
    
} catch (Exception $e) {
    error_log("Error saving HTML template: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
