<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\CmsPage;
use App\Models\AuditLog;

class CmsController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $model = new CmsPage();
        $pages = $model->getAll();
        $this->view('cms/index', ['pages' => $pages]);
    }

    public function edit($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }
        $slug = $params['slug'] ?? 'home';
        $model = new CmsPage();
        $page = $model->findBySlug($slug);

        if (!$page) {
            $_SESSION['error'] = 'Page not found';
            $this->redirect('/cms');
        }

        $settingModel = new \App\Models\Setting();
        $heroTitle = $settingModel->getValue('home_hero_title', 'Advancing Anaesthesiology in Ghana');
        $heroSubtitle = $settingModel->getValue('home_hero_subtitle', '');

        $this->view('cms/edit', [
            'page' => $page,
            'heroTitle' => $heroTitle,
            'heroSubtitle' => $heroSubtitle,
        ]);
    }

    public function update($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Access denied';
            $this->redirect('/dashboard');
        }

        $slug = $params['slug'] ?? 'home';
        $model = new CmsPage();
        $page = $model->findBySlug($slug);

        if (!$page) {
            $_SESSION['error'] = 'Page not found';
            $this->redirect('/cms');
        }

        $data = [
            'title' => $_POST['title'] ?? $page->title,
            'content' => $_POST['content'] ?? '',
            'meta_title' => $_POST['meta_title'] ?? '',
            'meta_description' => $_POST['meta_description'] ?? '',
            'status' => $_POST['status'] ?? 'draft',
            'updated_by' => Auth::id(),
        ];

        $model->updateContent($page->id, $data);

        if ($slug === 'home' && $data['status'] === 'published') {
            $settingModel = new \App\Models\Setting();
            if (!empty($_POST['hero_title'])) {
                $settingModel->setValue('home_hero_title', $_POST['hero_title']);
            }
            if (!empty($_POST['hero_subtitle'])) {
                $settingModel->setValue('home_hero_subtitle', $_POST['hero_subtitle']);
            }
        }

        $audit = new AuditLog();
        $audit->log(Auth::id(), 'cms.update', 'cms_pages', $page->id, "Updated CMS page: {$page->slug}");

        $_SESSION['success'] = "Page '{$data['title']}' updated successfully";
        $this->redirect('/cms');
    }
}
