<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\BirthdayWish;
use App\Models\User;

class BirthdayController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        Auth::requireLogin();
        $model = new BirthdayWish();
        $month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
        $members = $model->getBirthdayMembers($month);
        $currentMonth = $month;
        $monthName = date('F', mktime(0, 0, 0, $month, 1));

        $celebrants = [];
        foreach ($members as $m) {
            $celebrants[] = $m;
        }

        $this->view('birthdays/index', [
            'title' => 'Birthdays - ' . $monthName,
            'celebrants' => $celebrants,
            'currentMonth' => $currentMonth,
            'monthName' => $monthName,
            'birthdayFieldExists' => !empty($members) || $model->getBirthdayField() !== false,
        ]);
    }

    public function wishes($params)
    {
        Auth::requireLogin();
        $recipientId = $params['id'] ?? null;
        if (!$recipientId) {
            $this->redirect('/birthdays');
        }

        $userModel = new User();
        $recipient = $userModel->find($recipientId);
        if (!$recipient) {
            $this->redirect('/birthdays');
        }

        $model = new BirthdayWish();
        $wishes = $model->getWishesForUser($recipientId);

        $this->view('birthdays/wishes', [
            'title' => 'Birthday Wishes for ' . $recipient->name,
            'recipient' => $recipient,
            'wishes' => $wishes,
        ]);
    }

    public function sendWish($params)
    {
        Auth::requireLogin();
        $recipientId = $params['id'] ?? null;
        $message = trim($_POST['message'] ?? '');

        if (!$recipientId || empty($message)) {
            $_SESSION['error'] = 'Please enter a birthday message.';
            $this->redirect('/birthdays/wishes/' . $recipientId);
        }

        $model = new BirthdayWish();
        $model->sendWish($recipientId, Auth::id(), $message);

        $_SESSION['success'] = 'Your birthday wish has been sent!';
        $this->redirect('/birthdays/wishes/' . $recipientId);
    }
}
