<?php

/**
 * PWA Template Controller
 * Handles template selection for PWA
 */
class PwaTemplateController {
    
    private $templateModel;
    
    public function __construct() {
        $this->templateModel = new Template();
        $this->requireAuth();
    }
    
    /**
     * Display active templates
     */
    public function index() {
        $userId = getCurrentUserId();
        $templates = $this->templateModel->getActive();
        $defaultTemplate = $this->templateModel->getUserDefaultTemplate($userId);
        
        // Handle POST request to set default template
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $templateId = intval($_POST['template_id'] ?? 0);
            
            if ($templateId > 0) {
                $success = $this->templateModel->setUserDefaultTemplate($userId, $templateId);
                
                // Check if this is an AJAX request
                $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
                          strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
                
                if ($isAjax) {
                    // Return JSON for AJAX requests
                    header('Content-Type: application/json');
                    echo json_encode([
                        'success' => $success,
                        'message' => $success ? 'Default template updated successfully!' : 'Failed to update default template',
                        'template_id' => $templateId
                    ]);
                    exit;
                } else {
                    // Regular form submission - redirect
                    if ($success) {
                        $_SESSION['success'] = 'Default template updated successfully!';
                    } else {
                        $_SESSION['error'] = 'Failed to update default template';
                    }
                    
                    redirect(BASE_URL . '/templates');
                    return;
                }
            }
        }
        
        require_once APP_PATH . '/views/pwa/templates.php';
    }
    
    /**
     * Require authentication
     */
    private function requireAuth() {
        if (!isAuthenticated()) {
            redirect(BASE_URL . '/login');
            exit;
        }
    }
}
