<?php
/*
    goal_actions/assign_goal.php
    -----------------------------------------------------------------
    Handles form_action = assign_goal, included from compass_view.php.
    Expects $conn, $current_user_id, $month, $selectedFyId and the
    runCompass()/auditCompass() helpers to already be in scope.

    NOTE: If the same Goal Title (goal_library_id) is assigned again to the
    same Employee, compass_view.php's mergeDuplicateGoalsByLibrary() will
    automatically fold the two rows into ONE Goal card on the board (with
    all Indicators listed together) — no change needed here for that.
*/

try {
    $employeeId = (int)($_POST['employee_id'] ?? 0);
    $goalLibraryId = (int)($_POST['goal_library_id'] ?? 0);
    $goalType = $_POST['goal_type'] ?? 'Individual Goal';
    $goalWeightage = 0;
    $startDate = null;
    $endDate = null;

    if ($employeeId <= 0 || $goalLibraryId <= 0) {
        throw new Exception("Employee and Goal Title are mandatory.");
    }

    if (!in_array($goalType, ['Company Goal', 'Department Goal', 'Individual Goal'], true)) {
        $goalType = 'Individual Goal';
    }

    runCompass(
        $conn,
        "INSERT INTO compass_goals
         (employee_id, goal_library_id, goal_type, goal_status, goal_weightage, start_date, end_date, is_active, is_deleted, created_by, updated_by)
         VALUES (?, ?, ?, 'Launched', ?, ?, ?, 1, 0, ?, ?)",
        [$employeeId, $goalLibraryId, $goalType, $goalWeightage, $startDate, $endDate, $current_user_id, $current_user_id]
    )->close();

    $goalId = (int)$conn->insert_id;

    if (tableExistsCompass($conn, 'compass_goal_contributors')) {
        runCompass(
            $conn,
            "INSERT IGNORE INTO compass_goal_contributors
             (goal_id, user_id, contribution_percent, created_by, updated_by)
             VALUES (?, ?, 100, ?, ?)",
            [$goalId, $employeeId, $current_user_id, $current_user_id]
        )->close();
    }

    auditCompass($conn, $current_user_id, 'ASSIGN_GOAL', 'compass_goals', $goalId, 'Goal assigned.');

    header("Location:compass_view.php?mode=workspace&month=" . urlencode($month ?: currentFyMonthCode()) . "&assigned=1&fy=" . $selectedFyId);
    exit;

} catch (Exception $e) {
    $error = $e->getMessage();
}