<?php

namespace App\Controllers;

use App\Models\CountdownModel;
use App\Models\CommentModel;
use CodeIgniter\HTTP\ResponseInterface;

class CountdownController extends BaseController
{
    protected $countdownModel;
    protected $commentModel;

    public function __construct()
    {
        $this->countdownModel = new CountdownModel();
        $this->commentModel = new CommentModel();
    }

    public function index()
    {
        $targetDate = $this->countdownModel->getTargetDate();
        $comments = $this->commentModel->getAllComments();

        return view('countdown', [
            'targetDate' => $targetDate,
            'comments' => $comments
        ]);
    }

    public function fetchComments()
    {
        return $this->response->setJSON($this->commentModel->getAllComments());
    }

    public function postComment()
    {
        $data = [
            'username' => $this->request->getPost('username'),
            'message' => $this->request->getPost('message'),
        ];

        if ($this->commentModel->save($data)) {
            return $this->response->setJSON(['status' => 'success', 'message' => 'Comment added']);
        }
        
        return $this->response->setStatusCode(ResponseInterface::HTTP_BAD_REQUEST)
                              ->setJSON(['status' => 'error', 'message' => 'Failed to add comment']);
    }
}
