<?php
session_start();
require_once '../config/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $company_id = $_POST['company_id'];
    $upliner_ids = isset($_POST['upliner_ids']) ? $_POST['upliner_ids'] : [];

    if (empty($upliner_ids)) {
        $_SESSION['msg'] = "Please select at least one upliner.";
        $_SESSION['msg_type'] = "error";
        header("Location: assign-upliners.php");
        exit();
    }

    $success_count = 0;
    foreach ($upliner_ids as $u_id) {
        $u_id = $conn->real_escape_string($u_id);
        // INSERT IGNORE prevents errors if a link already exists
        $sql = "INSERT IGNORE INTO company_upliners (company_id, upliner_id) 
                VALUES ('$company_id', '$u_id')";
        
        if ($conn->query($sql)) {
            $success_count++;
        }
    }

    $_SESSION['msg'] = "Successfully linked $success_count upliners to the company.";
    $_SESSION['msg_type'] = "success";
    header("Location: ../assign-upliners.php");
    exit();
}