<?php

namespace App\Controllers\Admin;

use App\Models\PageModel;

class Pages extends AdminBaseController
{
    public function index()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new PageModel();
        $data['pages'] = $model->findAll();
        $data['title'] = 'Manage Pages';

        return view('admin/pages/index', $data);
    }

    public function edit($id)
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new PageModel();
        $page = $model->find($id);

        if (!$page) {
            $this->session->setFlashdata('error', 'Page not found.');
            return redirect()->to('/admin/pages');
        }

        if ($this->request->getMethod() === 'POST') {
            $updateData = [
                'title' => $this->request->getPost('title'),
                'heading' => $this->request->getPost('heading'),
                'content' => $this->request->getPost('content'),
                'meta_title' => $this->request->getPost('meta_title'),
                'meta_description' => $this->request->getPost('meta_description'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            if ($model->update($id, $updateData)) {
                $this->session->setFlashdata('success', 'Page updated successfully.');
                return redirect()->to('/admin/pages');
            } else {
                $this->session->setFlashdata('error', 'Failed to update page.');
            }
        }

        $data['page'] = $page;
        $data['title'] = 'Edit Page: ' . $page['title'];

        return view('admin/pages/edit', $data);
    }
}
