<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Check if user is admin
if (!isAdmin($user['id'])) {
    errorResponse('Unauthorized: Admin access required', 403);
}

// Validate action
if (!isset($input['action'])) {
    errorResponse('Action is required', 400);
}

$action = $input['action'];

try {
    switch ($action) {
        case 'create':
            $templateData = isset($input['templateData']) ? $input['templateData'] : null;
            
            if (!$templateData || !isset($templateData['name']) || !isset($templateData['subject']) || !isset($templateData['content']) || !isset($templateData['template_type'])) {
                errorResponse('Name, subject, content, and template_type are required', 400);
            }
            
            $id = generateUUID();
            $stmt = $pdo->prepare("INSERT INTO email_templates (id, name, subject, content, template_type, is_active, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $id,
                $templateData['name'],
                $templateData['subject'],
                $templateData['content'],
                $templateData['template_type'],
                isset($templateData['is_active']) ? $templateData['is_active'] : true,
                $user['id']
            ]);
            
            // Fetch the created template
            $stmt = $pdo->prepare("SELECT * FROM email_templates WHERE id = ?");
            $stmt->execute([$id]);
            $template = $stmt->fetch();
            
            jsonResponse(['template' => $template], 200);
            break;
            
        case 'list':
            $stmt = $pdo->prepare("SELECT et.*, u.email as created_by_email FROM email_templates et LEFT JOIN users u ON et.created_by = u.id ORDER BY et.created_at DESC");
            $stmt->execute();
            $templates = $stmt->fetchAll();
            
            jsonResponse(['templates' => $templates], 200);
            break;
            
        case 'get':
            $id = isset($input['id']) ? $input['id'] : null;
            
            if (!$id) {
                errorResponse('Template ID is required', 400);
            }
            
            $stmt = $pdo->prepare("SELECT * FROM email_templates WHERE id = ?");
            $stmt->execute([$id]);
            $template = $stmt->fetch();
            
            if (!$template) {
                errorResponse('Template not found', 404);
            }
            
            jsonResponse(['template' => $template], 200);
            break;
            
        case 'update':
            $id = isset($input['id']) ? $input['id'] : null;
            $templateData = isset($input['templateData']) ? $input['templateData'] : null;
            
            if (!$id) {
                errorResponse('Template ID is required', 400);
            }
            
            if (!$templateData) {
                errorResponse('Template data is required', 400);
            }
            
            $updates = [];
            $params = [];
            
            if (isset($templateData['name'])) {
                $updates[] = "name = ?";
                $params[] = $templateData['name'];
            }
            
            if (isset($templateData['subject'])) {
                $updates[] = "subject = ?";
                $params[] = $templateData['subject'];
            }
            
            if (isset($templateData['content'])) {
                $updates[] = "content = ?";
                $params[] = $templateData['content'];
            }
            
            if (isset($templateData['template_type'])) {
                $updates[] = "template_type = ?";
                $params[] = $templateData['template_type'];
            }
            
            if (isset($templateData['is_active'])) {
                $updates[] = "is_active = ?";
                $params[] = $templateData['is_active'];
            }
            
            if (empty($updates)) {
                errorResponse('No valid fields to update', 400);
            }
            
            $params[] = $id;
            $sql = "UPDATE email_templates SET " . implode(", ", $updates) . ", updated_at = datetime('now') WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            // Fetch the updated template
            $stmt = $pdo->prepare("SELECT * FROM email_templates WHERE id = ?");
            $stmt->execute([$id]);
            $template = $stmt->fetch();
            
            jsonResponse(['template' => $template], 200);
            break;
            
        case 'delete':
            $id = isset($input['id']) ? $input['id'] : null;
            
            if (!$id) {
                errorResponse('Template ID is required', 400);
            }
            
            $stmt = $pdo->prepare("DELETE FROM email_templates WHERE id = ?");
            $stmt->execute([$id]);
            
            jsonResponse(['success' => true], 200);
            break;
            
        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error managing email templates: ' . $e->getMessage(), 500);
}
?>