<?php

namespace App\Modules\Admin\Controllers;

use App\Modules\Admin\Models\BlogModel;
use CodeIgniter\Controller;

class BlogController extends Controller
{
    protected $blogModel;

    public function __construct()
    {
        $this->blogModel = new BlogModel();
    }

    /**
     * Display the list of stories with filtering and pagination
     */
    public function index()
    {
        $status = $this->request->getGet('status');
        
        // Use the model helper we created to get the query builder
        $query = $this->blogModel->getFilteredPosts($status ?? 'all');

        $data = [
            'posts'        => $query->paginate(10),
            'pager'        => $this->blogModel->pager,
            'statusFilter' => $status ?? 'all',
        ];

        return view('App\Modules\Admin\Views\blog\index', $data);
    }

    public function create()
    {
        return view('App\Modules\Admin\Views\blog\form', ['post' => null]);
    }

    public function edit(int $id)
    {
        $post = $this->blogModel->find($id);
        
        if (!$post) {
            return redirect()->to(url_to('admin.blog.index'))->with('error', 'Story not found on the trail.');
        }
        
        return view('App\Modules\Admin\Views\blog\form', ['post' => $post]);
    }

    public function store()
    {
        return $this->savePost();
    }

    public function update(int $id)
    {
        return $this->savePost($id);
    }

    /**
     * Logic for saving or updating a story
     */
    private function savePost(?int $id = null)
    {
        // Validation rules
        $rules = [
            'title'   => 'required|min_length[3]|max_length[255]',
            'content' => 'required',
            'status'  => 'required|in_list[draft,published]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('error', 'Please check the required fields.');
        }

        $data = [
            'title'            => $this->request->getPost('title'),
            'slug'             => $this->request->getPost('slug'),
            'excerpt'          => $this->request->getPost('excerpt'),
            'content'          => $this->request->getPost('content'), // Quill HTML data
            'image'            => $this->request->getPost('image'),
            'category'         => $this->request->getPost('category'),
            'tags'             => $this->request->getPost('tags'),
            'meta_title'       => $this->request->getPost('meta_title'),
            'meta_description' => $this->request->getPost('meta_description'),
            'status'           => $this->request->getPost('status') ?? 'draft',
        ];

        try {
            if ($id) {
                $this->blogModel->update($id, $data);
                $message = 'Chronicle updated successfully.';
            } else {
                $this->blogModel->insert($data);
                $message = 'New story published to the trail.';
            }
        } catch (\Exception $e) {
            return redirect()->back()->withInput()->with('error', 'Database Error: ' . $e->getMessage());
        }

        return redirect()->to(url_to('admin.blog.index'))->with('success', $message);
    }

    public function delete(int $id)
    {
        if ($this->blogModel->delete($id)) {
            return redirect()->to(url_to('admin.blog.index'))->with('success', 'Post removed from records.');
        }
        
        return redirect()->to(url_to('admin.blog.index'))->with('error', 'Could not delete the post.');
    }
}