<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth.php';

// APIは302禁止：未ログインは401 JSON
require_login_json();

$DEBUG_VER = 'tasks_get_2026-01-08_FINAL';

function json_out(array $data, int $code = 200): void
{
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function normalize_assignee_user_ids($v): array
{
    if (is_array($v)) {
        $arr = $v;
    } else {
        $raw = (string)$v;
        $arr = ($raw !== '') ? json_decode($raw, true) : [];
        if (!is_array($arr)) $arr = [];
    }
    return array_values(array_filter(array_map('intval', $arr), fn($n) => $n > 0));
}

$task_id = isset($_GET['task_id']) ? (int)$_GET['task_id'] : 0;
if ($task_id <= 0) {
    json_out(['ok'=>false,'debug_ver'=>$DEBUG_VER,'error'=>'invalid_task_id'], 400);
}

try {
    $pdo = db();

    // ===== tasks を取得（Unknown column が出たら列を落として再試行）=====
    // DBの正式：task_title/task_detail を含め、返却用 title/body も用意して正規化する
    $cols = [
        'id','status','customer_id',
        'task_title','task_detail',
        'due_date','return_reason',
        'assignee_user_ids'
    ];

    $task = null;

    for ($i=0; $i<8; $i++) {
        $select = implode(", ", array_map(fn($c)=>"`$c`", $cols));
        $sql = "SELECT $select FROM tasks WHERE id = :id LIMIT 1";

        try {
            $st = $pdo->prepare($sql);
            $st->execute([':id' => $task_id]);
            $task = $st->fetch(PDO::FETCH_ASSOC);
            break;

        } catch (Throwable $e) {
            // Unknown column 'xxx' → その列を落としてリトライ
            if (preg_match("/Unknown column '([^']+)'/u", $e->getMessage(), $m)) {
                $bad = $m[1];
                $cols = array_values(array_filter($cols, fn($c) => $c !== $bad));
                if (!$cols) throw $e;
                continue;
            }
            throw $e;
        }
    }

    if (!$task) {
        json_out(['ok'=>false,'debug_ver'=>$DEBUG_VER,'error'=>'not_found'], 404);
    }

    // 返却キーを安定させる（UI側が参照しても落ちない）
    $defaults = [
        'id'=>null,
        'status'=>null,
        'customer_id'=>null,
        'task_title'=>null,
        'task_detail'=>null,
        'due_date'=>null,
        'return_reason'=>null,
        'assignee_user_ids'=>null,

        // 返却互換キー（UI/既存JSが title/body を期待してもOKにする）
        'title'=>null,
        'body'=>null,
    ];
    $task = array_merge($defaults, $task);

    // 型整形
    if ($task['id'] !== null) $task['id'] = (int)$task['id'];
    if ($task['customer_id'] !== null) $task['customer_id'] = (int)$task['customer_id'];

    // title/body を DB正式カラムから正規化
    if (($task['title'] === null || $task['title'] === '') && $task['task_title'] !== null) {
        $task['title'] = (string)$task['task_title'];
    }
    if (($task['body'] === null || $task['body'] === '') && $task['task_detail'] !== null) {
        $task['body'] = (string)$task['task_detail'];
    }

    // assignee_user_ids を配列化
    $assignees = normalize_assignee_user_ids($task['assignee_user_ids']);
    $task['assignee_user_ids'] = $assignees;

    // ===== 表示用（顧客名・部署名・担当者名）=====
    $task['customer_name']   = null;
    $task['department_name'] = null;
    $task['assignees']       = [];

    // customers / departments（存在しない・列がない場合も落とさない）
    if (!empty($task['customer_id'])) {
        try {
            // department_id がある場合と無い場合で分ける
            try {
                $cst = $pdo->prepare("SELECT `name`, `department_id` FROM customers WHERE id = :id LIMIT 1");
                $cst->execute([':id' => (int)$task['customer_id']]);
                $c = $cst->fetch(PDO::FETCH_ASSOC);
            } catch (Throwable $e2) {
                $cst = $pdo->prepare("SELECT `name` FROM customers WHERE id = :id LIMIT 1");
                $cst->execute([':id' => (int)$task['customer_id']]);
                $c = $cst->fetch(PDO::FETCH_ASSOC);
            }

            if (!empty($c['name'])) $task['customer_name'] = $c['name'];

            if (!empty($c['department_id'])) {
                try {
                    $dst = $pdo->prepare("SELECT `name` FROM departments WHERE id = :id LIMIT 1");
                    $dst->execute([':id' => (int)$c['department_id']]);
                    $d = $dst->fetch(PDO::FETCH_ASSOC);
                    if (!empty($d['name'])) $task['department_name'] = $d['name'];
                } catch (Throwable $e3) {
                    // departments が無い等：スキップ
                }
            }
        } catch (Throwable $eC) {
            // customers が無い等：スキップ
        }
    }

    // users（display_name が無ければ login_id で代替）
    if ($assignees) {
        $in = implode(',', array_fill(0, count($assignees), '?'));
        try {
            try {
                $ust = $pdo->prepare("SELECT `id`, `display_name` AS `name` FROM users WHERE id IN ($in)");
                $ust->execute($assignees);
            } catch (Throwable $eU1) {
                $ust = $pdo->prepare("SELECT `id`, `login_id` AS `name` FROM users WHERE id IN ($in)");
                $ust->execute($assignees);
            }

            $rows = $ust->fetchAll(PDO::FETCH_ASSOC);
            $map = [];
            foreach ($rows as $r) {
                $map[(int)$r['id']] = (string)($r['name'] ?? '');
            }
            foreach ($assignees as $uid) {
                if (!empty($map[$uid])) $task['assignees'][] = $map[$uid];
            }
        } catch (Throwable $eU) {
            // users が無い等：スキップ
        }
    }

    json_out(['ok'=>true,'debug_ver'=>$DEBUG_VER,'task'=>$task]);

} catch (Throwable $e) {
    error_log('[tasks_get] '.$e->getMessage().' @ '.$e->getFile().':'.$e->getLine());
    json_out(['ok'=>false,'debug_ver'=>$DEBUG_VER,'error'=>'server_error'], 500);
}
