<?php

/**
 * Template Controller
 * Handles template management (CRUD operations)
 */
class TemplateController {
    
    private $authController;
    private $templateModel;
    
    public function __construct() {
        $this->authController = new AuthController();
        $this->authController->requireAuth();
        
        $this->templateModel = new Template();
    }
    
    /**
     * List all templates
     */
    public function index() {
        $pageTitle = 'Templates';
        
        // Get all templates
        $templates = $this->templateModel->getAll();
        
        require_once APP_PATH . '/views/admin/templates/index.php';
    }
    
    /**
     * Show create template form
     */
    public function create() {
        $pageTitle = 'Add New Template';
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        require_once APP_PATH . '/views/admin/templates/create.php';
    }
    
    /**
     * Store new template
     */
    private function store() {
        // Get and sanitize input
        $name = sanitize($_POST['name'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $content = sanitize($_POST['content'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        
        // Validation
        $errors = [];
        
        if (empty($name)) {
            $errors[] = 'Template name is required';
        }
        
        if (empty($content)) {
            $errors[] = 'Template content is required';
        }
        
        if (!in_array($status, ['active', 'inactive'])) {
            $errors[] = 'Invalid status value';
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Add New Template';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/templates/create.php';
            return;
        }
        
        // Create template
        $templateId = $this->templateModel->create([
            'name' => $name,
            'description' => $description,
            'content' => $content,
            'status' => $status
        ]);
        
        if ($templateId) {
            $_SESSION['success'] = 'Template created successfully';
            redirect(BASE_URL . '/admin/templates');
        } else {
            $pageTitle = 'Add New Template';
            $errorMessage = 'Failed to create template';
            require_once APP_PATH . '/views/admin/templates/create.php';
        }
    }
    
    /**
     * Show edit template form
     */
    public function edit($id) {
        $pageTitle = 'Edit Template';
        
        // Get template
        $template = $this->templateModel->findById($id);
        
        if (!$template) {
            redirect(BASE_URL . '/admin/templates?error=' . urlencode('Template not found'));
            return;
        }
        
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->update($id);
            return;
        }
        
        require_once APP_PATH . '/views/admin/templates/edit.php';
    }
    
    /**
     * Update template
     */
    private function update($id) {
        // Get template
        $template = $this->templateModel->findById($id);
        
        if (!$template) {
            redirect(BASE_URL . '/admin/templates?error=' . urlencode('Template not found'));
            return;
        }
        
        // Get and sanitize input
        $name = sanitize($_POST['name'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $content = sanitize($_POST['content'] ?? '');
        $status = sanitize($_POST['status'] ?? 'active');
        
        // Validation
        $errors = [];
        
        if (empty($name)) {
            $errors[] = 'Template name is required';
        }
        
        if (empty($content)) {
            $errors[] = 'Template content is required';
        }
        
        if (!in_array($status, ['active', 'inactive'])) {
            $errors[] = 'Invalid status value';
        }
        
        if (!empty($errors)) {
            $pageTitle = 'Edit Template';
            $errorMessage = implode('<br>', $errors);
            require_once APP_PATH . '/views/admin/templates/edit.php';
            return;
        }
        
        // Update template
        $result = $this->templateModel->update($id, [
            'name' => $name,
            'description' => $description,
            'content' => $content,
            'status' => $status
        ]);
        
        if ($result) {
            $_SESSION['success'] = 'Template updated successfully';
            redirect(BASE_URL . '/admin/templates');
        } else {
            $pageTitle = 'Edit Template';
            $errorMessage = 'Failed to update template';
            require_once APP_PATH . '/views/admin/templates/edit.php';
        }
    }
    
    /**
     * Delete template
     */
    public function delete($id) {
        // Delete template
        $result = $this->templateModel->delete($id);
        
        if ($result) {
            $_SESSION['success'] = 'Template deleted successfully';
            redirect(BASE_URL . '/admin/templates');
        } else {
            $_SESSION['error'] = 'Failed to delete template';
            redirect(BASE_URL . '/admin/templates');
        }
    }
    
    /**
     * Toggle template status
     */
    public function toggle($id) {
        $result = $this->templateModel->toggleStatus($id);
        
        if ($result) {
            $_SESSION['success'] = 'Template status updated';
            redirect(BASE_URL . '/admin/templates');
        } else {
            $_SESSION['error'] = 'Failed to update status';
            redirect(BASE_URL . '/admin/templates');
        }
    }
}
