<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Validator;
use App\Models\Meeting;
use App\Services\RecordService;

final class CalendarController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('calendar');
        $month = (int) ($_GET['month'] ?? date('n'));
        $year = (int) ($_GET['year'] ?? date('Y'));
        if ($month < 1 || $month > 12) {
            $month = (int) date('n');
        }
        $start = sprintf('%04d-%02d-01 00:00:00', $year, $month);
        $end = date('Y-m-d H:i:s', strtotime("$start +1 month"));
        $scope = has_role('manager') ? null : $this->ownerScope();
        view('calendar/index', [
            'title' => 'Calendar',
            'month' => $month,
            'year' => $year,
            'events' => Meeting::inRange($start, $end, $scope),
            'counts' => Meeting::monthCounts($year, $month, $scope),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('calendar');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())->required($data, ['title' => 'Title', 'starts_at' => 'Start']);
        if ($v->fails()) {
            $this->fail($v);
        }
        $relatedType = trim((string) ($data['related_type'] ?? ''));
        $relatedId = (int) ($data['related_id'] ?? 0);
        $meetingType = (string) ($data['meeting_type'] ?? 'meeting');
        if (!in_array($meetingType, ['call', 'meeting', 'visit', 'other'], true)) {
            $meetingType = 'meeting';
        }
        $id = Meeting::create([
            'title' => $data['title'],
            'starts_at' => date('Y-m-d H:i:s', strtotime((string) $data['starts_at'])),
            'ends_at' => !empty($data['ends_at']) ? date('Y-m-d H:i:s', strtotime((string) $data['ends_at'])) : null,
            'location' => trim((string) ($data['location'] ?? '')) ?: null,
            'meeting_type' => $meetingType,
            'related_type' => $relatedType !== '' ? $relatedType : null,
            'related_id' => $relatedId > 0 ? $relatedId : null,
            'owner_id' => Auth::instance()->id(),
            'notes' => trim((string) ($data['notes'] ?? '')) ?: null,
        ]);
        RecordService::logActivity(
            $meetingType === 'call' ? 'call' : ($meetingType === 'visit' ? 'visit' : 'meeting'),
            $data['title'],
            $data['notes'] ?? null,
            $relatedType !== '' ? $relatedType : null,
            $relatedId > 0 ? $relatedId : null
        );
        json_out(['ok' => true, 'id' => $id]);
    }
}
