<?php

require_once APP_ROOT . '/models/ListNote.php';

class ListController
{
    private ListNote $listModel;

    public function __construct()
    {
        if (!Session::isLoggedIn()) {
            header('Location: ' . APP_URL . '/login');
            exit;
        }
        $this->listModel = new ListNote();
    }

    public function index(): void
    {
        $lists = $this->listModel->getAllByUser(Session::getUserId());
        require APP_ROOT . '/views/lists/index.php';
    }

    public function create(): void
    {
        require APP_ROOT . '/views/lists/create.php';
    }

    public function store(): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/lists');
            exit;
        }

        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');

        $validator = new Validator();
        $validator->required('title', $title, Lang::get('list_title'));

        if ($validator->fails()) {
            Session::flash('error', $validator->firstError());
            header('Location: ' . APP_URL . '/lists/create');
            exit;
        }

        $reminderEmail = trim($_POST['reminder_email'] ?? '');
        $reminderDate = trim($_POST['reminder_date'] ?? '');
        $reminderTime = trim($_POST['reminder_time'] ?? '');
        $reminderAt = null;
        if (!empty($reminderDate) && !empty($reminderTime)) {
            $reminderAt = $reminderDate . ' ' . $reminderTime . ':00';
        }

        $this->listModel->create([
            'user_id'        => Session::getUserId(),
            'title'          => $title,
            'content'        => $content,
            'reminder_email' => !empty($reminderEmail) ? $reminderEmail : null,
            'reminder_at'    => $reminderAt,
        ]);

        Session::flash('success', Lang::get('list_created'));
        header('Location: ' . APP_URL . '/lists');
        exit;
    }

    public function edit(string $id): void
    {
        $list = $this->listModel->findById((int)$id);
        if (!$list) {
            header('Location: ' . APP_URL . '/lists');
            exit;
        }
        require APP_ROOT . '/views/lists/edit.php';
    }

    public function update(string $id): void
    {
        if (!Session::verifyCsrfToken($_POST['csrf_token'] ?? '')) {
            Session::flash('error', 'Invalid request.');
            header('Location: ' . APP_URL . '/lists/' . $id . '/edit');
            exit;
        }

        $title = trim($_POST['title'] ?? '');
        $content = trim($_POST['content'] ?? '');

        $validator = new Validator();
        $validator->required('title', $title, Lang::get('list_title'));

        if ($validator->fails()) {
            Session::flash('error', $validator->firstError());
            header('Location: ' . APP_URL . '/lists/' . $id . '/edit');
            exit;
        }

        $reminderEmail = trim($_POST['reminder_email'] ?? '');
        $reminderDate = trim($_POST['reminder_date'] ?? '');
        $reminderTime = trim($_POST['reminder_time'] ?? '');
        $reminderAt = null;
        if (!empty($reminderDate) && !empty($reminderTime)) {
            $reminderAt = $reminderDate . ' ' . $reminderTime . ':00';
        }

        $existingList = $this->listModel->findById((int)$id);
        $reminderSent = ($existingList && $existingList['reminder_at'] !== $reminderAt) ? 0 : ($existingList['reminder_sent'] ?? 0);

        $this->listModel->update((int)$id, [
            'title'          => $title,
            'content'        => $content,
            'reminder_email' => !empty($reminderEmail) ? $reminderEmail : null,
            'reminder_at'    => $reminderAt,
            'reminder_sent'  => $reminderSent,
        ]);

        Session::flash('success', Lang::get('list_updated'));
        header('Location: ' . APP_URL . '/lists');
        exit;
    }

    public function delete(string $id): void
    {
        $this->listModel->delete((int)$id);
        Session::flash('success', Lang::get('list_deleted'));
        header('Location: ' . APP_URL . '/lists');
        exit;
    }

    public function moveUp(string $id): void
    {
        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
        $result = $this->listModel->moveUp((int)$id, Session::getUserId());

        if ($isAjax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => $result]);
            exit;
        }

        if ($result) {
            Session::flash('success', Lang::get('item_moved_up'));
        } else {
            Session::flash('error', Lang::get('cannot_move_item'));
        }
        header('Location: ' . APP_URL . '/lists');
        exit;
    }

    public function moveDown(string $id): void
    {
        $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
        $result = $this->listModel->moveDown((int)$id, Session::getUserId());

        if ($isAjax) {
            header('Content-Type: application/json');
            echo json_encode(['success' => $result]);
            exit;
        }

        if ($result) {
            Session::flash('success', Lang::get('item_moved_down'));
        } else {
            Session::flash('error', Lang::get('cannot_move_item'));
        }
        header('Location: ' . APP_URL . '/lists');
        exit;
    }
}
