<?php
require_once 'lib/ErrorHandler.php';
register_error_handler();

require_once 'db/config.php';
require_once 'WorkflowEngine.php';

session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    throw new WorkflowException('You must be logged in to perform this action.', 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    throw new WorkflowException('Invalid request method.', 405);
}

$personId = $_POST['person_id'] ?? null;
$bniGroupId = $_POST['bni_group_id'] ?? $_POST['group_id'] ?? null;
$meetingDate = $_POST['meeting_date'] ?? null;
$status = $_POST['attendance_status'] ?? null;
$guestSurvey = $_POST['guest_survey'] ?? null;
$userId = $_SESSION['user_id'];

if (!$personId || !$bniGroupId || !$meetingDate || !$status) {
    $missing_params = [];
    if (!$personId) $missing_params[] = 'person_id';
    if (!$bniGroupId) $missing_params[] = 'bni_group_id';
    if (!$meetingDate) $missing_params[] = 'meeting_date';
    if (!$status) $missing_params[] = 'status';
    throw new WorkflowException('Missing required parameters: ' . implode(', ', $missing_params), 400);
}

$workflowEngine = new WorkflowEngine();

$meetingId = $workflowEngine->getOrCreateMeeting((int)$bniGroupId, $meetingDate);
$workflowEngine->updateMeetingAttendance($meetingId, (int)$personId, (int)$bniGroupId, $status, (int)$userId, $guestSurvey);

$response = [
    'success' => true,
    'message' => 'Attendance updated successfully.'
];

echo json_encode($response);

