<?php

namespace App\Controllers\Admin;

use App\Models\PageModel;

class Pages extends BaseController
{
    protected $pageModel;

    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
        $this->pageModel = new PageModel();
    }

    public function index()
    {
        $this->data['title'] = 'Halaman Statis';
        $this->data['items'] = $this->pageModel->orderBy('created_at', 'DESC')->paginate(10);
        $this->data['pager'] = $this->pageModel->pager;

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

    public function new()
    {
        $this->data['title'] = 'Tambah Halaman';
        $this->data['item']  = [];

        return view('admin/pages/form', $this->data);
    }

    public function create()
    {
        $data = $this->request->getPost();
        $data['slug']   = url_title($data['title'] ?? '', '-', true);
        $data['status'] = $data['status'] ?? 'draft';

        if (!$this->pageModel->insert($data)) {
            return redirect()->back()->withInput()->with('error', 'Gagal menyimpan halaman.');
        }

        $pageId = $this->pageModel->getInsertID();

        if (!empty($data['add_to_menu'])) {
            $menuModel = new \App\Models\MenuItemModel();
            $menuModel->insert([
                'title'      => $data['title'],
                'url'        => $data['slug'],
                'target'     => '_self',
                'sort_order' => 0,
                'status'     => $data['status'] === 'published' ? 1 : 0,
                'type'       => 'page',
                'page_id'    => $pageId,
            ]);
        }

        return redirect()->to('/admin/pages')->with('success', 'Halaman berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $this->data['title'] = 'Edit Halaman';
        $this->data['item']  = $this->pageModel->find($id);

        if (!$this->data['item']) {
            return redirect()->to('/admin/pages')->with('error', 'Halaman tidak ditemukan.');
        }

        $menuModel = new \App\Models\MenuItemModel();
        $this->data['menuItem'] = $menuModel->where('page_id', $id)->first();

        return view('admin/pages/form', $this->data);
    }

    public function update($id)
    {
        $data = $this->request->getPost();
        $data['status'] = $data['status'] ?? 'draft';

        if ($data['title'] ?? null) {
            $data['slug'] = url_title($data['title'], '-', true);
        }

        if (!$this->pageModel->update($id, $data)) {
            return redirect()->back()->withInput()->with('error', 'Gagal memperbarui halaman.');
        }

        $menuModel = new \App\Models\MenuItemModel();
        $menuItem  = $menuModel->where('page_id', $id)->first();

        if (!empty($data['add_to_menu'])) {
            if ($menuItem) {
                $menuModel->update($menuItem['id'], [
                    'title'  => $data['title'],
                    'url'    => $data['slug'],
                    'status' => $data['status'] === 'published' ? 1 : 0,
                ]);
            } else {
                $menuModel->insert([
                    'title'      => $data['title'],
                    'url'        => $data['slug'],
                    'target'     => '_self',
                    'sort_order' => 0,
                    'status'     => $data['status'] === 'published' ? 1 : 0,
                    'type'       => 'page',
                    'page_id'    => $id,
                ]);
            }
        } elseif ($menuItem) {
            $menuModel->update($menuItem['id'], [
                'type'    => 'custom',
                'page_id' => null,
            ]);
        }

        return redirect()->to('/admin/pages')->with('success', 'Halaman berhasil diperbarui.');
    }

    public function delete($id)
    {
        $menuModel = new \App\Models\MenuItemModel();
        $menuItem  = $menuModel->where('page_id', $id)->first();

        if ($menuItem) {
            $menuModel->update($menuItem['id'], [
                'type'    => 'custom',
                'page_id' => null,
            ]);
        }

        if (!$this->pageModel->delete($id)) {
            return redirect()->to('/admin/pages')->with('error', 'Gagal menghapus halaman.');
        }

        return redirect()->to('/admin/pages')->with('success', 'Halaman berhasil dihapus.');
    }
}
