<?php

use App\Models\Page;
use App\Models\SeoMeta;
use App\Models\Faq;
use App\Enums\PageLayout;

$pageModel = new Page();
$seoMetaModel = new SeoMeta();
$faqModel = new Faq();
$action = $_GET['action'] ?? 'list';
$id = $_GET['id'] ?? $_POST['id'] ?? null;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST;
    // Generate slug from name if not provided
    if (empty($data['slug']) && !empty($data['name'])) {
        $data['slug'] = getSlug($data['name']);
    }
    
    // Validate layout
    if (!empty($data['layout']) && !PageLayout::isValid($data['layout'])) {
        $data['layout'] = PageLayout::Default->value;
    }
    
    // Handle extra_fields
    $data['extra_fields'] = $data['extra_fields'] ?? [];
    
    // Get action from form data
    $formAction = $data['action'] ?? $action;
    try {
        switch ($formAction) {
            case 'create':
            case 'edit':
                $pageId = $pageModel->updateOrCreate($data['slug'], $data);
                
                // Save SEO data if provided
                if (!empty($data['seo'])) {
                    $seoMetaModel->updateOrCreate('Page', $pageId, $data['seo']);
                }
                
                // Save FAQ data if provided
                if (!empty($data['faq'])) {
                    $faqData = [
                        'title' => $data['faq']['title'] ?? '',
                        'extra_fields' => $data['faq']['items'] ?? []
                    ];
                    $faqModel->updateOrCreate('page', $pageId, $faqData);
                }
                header("Location: /admin/pages/?action=edit&id=" . $pageId);exit;

                break;
                
            case 'delete':
                if ($id) {
                    $pageModel->delete($id);
                    // Delete associated SEO data
                    $seoMetaModel->deleteForRecord('page', $id);
                    $success = "Page deleted successfully!";
                    $action = 'list'; // Redirect to list
                }
                break;
        }
    } catch (Exception $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Get data for different actions
switch ($action) {
    case 'create':
    case 'new':
        $page = [
            'name' => '',
            'slug' => '',
            'title' => '',
            'content' => '',
            'extra_fields' => [],
            'layout' => PageLayout::Default->value,
            'is_homepage' => 0
        ];
        $action = 'create';
        break;
        
    case 'edit':
        if (!$id) {
            $action = 'list';
            break;
        }
        
        $page = $pageModel->getById($id);
        if (!$page) {
            $error = "Page not found!";
            $action = 'list';
            break;
        }
        
        // Load SEO data
        $seoMeta = $seoMetaModel->getForRecord('page', $id) ?: [];
        
        // Load FAQ data
        $faqData = $faqModel->getForRecord('page', $id);
        $faqs = !empty($faqData) && is_array($faqData) ? $faqData[0] : [];
        break;
        
    case 'list':
    default:
        $pages = $pageModel->getAll();
        $action = 'list';
        break;
}

// Get available layouts
$layouts = PageLayout::selectOptions();

// Determine which template to use
$template = match($action) {
    'list' => 'admin/pages/list.php',
    'create', 'edit' => 'admin/pages/form.php',
    default => 'admin/pages/list.php'
};

return ViewRender($template, [
    'action' => $action,
    'pages' => $pages ?? [],
    'page' => $page ?? null,
    'seoMeta' => $seoMeta ?? [],
    'faqs' => $faqs ?? [],
    'layouts' => $layouts,
    'success' => $success ?? null,
    'error' => $error ?? null
]);