<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../services/db.php";

$conn = db();

if (!$conn) {
    http_response_code(500);
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}

// 1. Get session token
$token = $_COOKIE['session'] ?? null;
if (!$token) {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        $token = $matches[1];
    }
}

if (!$token) {
    http_response_code(401);
    echo json_encode(["error" => "Unauthenticated"]);
    exit;
}

// 2. Resolve logged-in user details from sessions + users tables
$sessionSql = "SELECT u.id, u.name, u.email 
               FROM sessions s 
               JOIN users u ON s.user_id = u.id 
               WHERE s.token = ?";
$sessionStmt = sqlsrv_query($conn, $sessionSql, [$token]);

if ($sessionStmt === false || !($user = sqlsrv_fetch_array($sessionStmt, SQLSRV_FETCH_ASSOC))) {
    http_response_code(401);
    echo json_encode(["error" => "Invalid or expired session"]);
    exit;
}

// 3. Read request body
$input = json_decode(file_get_contents("php://input"), true);
$taskId = $input['task_id'] ?? null;

if (!$taskId) {
    http_response_code(400);
    echo json_encode(["error" => "Missing task_id"]);
    exit;
}

// 4. Update task assignee_id in SQL Server
$updateSql = "UPDATE tasks SET assignee_id = ? WHERE id = ?";
$updateStmt = sqlsrv_query($conn, $updateSql, [$user['id'], $taskId]);

if ($updateStmt === false) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to update task assignee", "details" => sqlsrv_errors()]);
    exit;
}

// 5. Return success payload with full user identity
echo json_encode([
    "success" => true,
    "task_id" => (int)$taskId,
    "user" => [
        "id" => (int)$user['id'],
        "name" => $user['name'],
        "email" => $user['email']
    ]
]);