<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/csrf.php";

error_reporting(0);

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$userId = (int)($_SESSION["user"]["id"] ?? 0);
$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);
$method = $_SERVER["REQUEST_METHOD"] ?? "GET";

function userDisplayName(array $row, string $nameKey, string $emailKey, string $fallbackPrefix, string $idKey): string {
    $name = trim((string)($row[$nameKey] ?? ""));
    if ($name !== "") return $name;
    $email = trim((string)($row[$emailKey] ?? ""));
    if ($email !== "") return $email;
    return $fallbackPrefix . " #" . (int)($row[$idKey] ?? 0);
}

if ($method === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(["success" => false, "error" => "invalid_payload"]);
        exit;
    }

    if (!requireCsrfFromPayload($data, "csrf")) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "invalid_csrf"]);
        exit;
    }

    if (!in_array($roleId, [1, 4, 5], true)) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "forbidden"]);
        exit;
    }

    $workerId = (int)($data["worker_id"] ?? 0);
    if ($workerId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "invalid_worker_id"]);
        exit;
    }

    $workerStmt = $pdo->prepare("
        SELECT w.id
        FROM workers w
        WHERE w.id = ?
        LIMIT 1
    ");
    $workerStmt->execute([$workerId]);
    if (!$workerStmt->fetch(PDO::FETCH_ASSOC)) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "worker_not_found"]);
        exit;
    }

    $companyId = 0;
    if ($roleId === 4) {
        $companyId = $userId;
    } else {
        $companyId = (int)($data["company_id"] ?? 0);
        if ($companyId <= 0) {
            $reqLookup = $pdo->prepare("
                SELECT company_id
                FROM requests
                WHERE worker_id = ? AND status = 'pending'
                ORDER BY id DESC
                LIMIT 1
            ");
            $reqLookup->execute([$workerId]);
            $companyId = (int)$reqLookup->fetchColumn();
        }
    }

    if ($companyId <= 0) {
        http_response_code(422);
        echo json_encode(["success" => false, "error" => "company_required"]);
        exit;
    }

    $companyCheck = $pdo->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
    $companyCheck->execute([$companyId]);
    if (!(int)$companyCheck->fetchColumn()) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "company_not_found"]);
        exit;
    }

    $matchedFor = (int)($data["matched_for"] ?? 0);
    if ($matchedFor <= 0) {
        $matchedFor = $companyId;
    }

    $matchedForCheck = $pdo->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
    $matchedForCheck->execute([$matchedFor]);
    if (!(int)$matchedForCheck->fetchColumn()) {
        http_response_code(404);
        echo json_encode(["success" => false, "error" => "matched_for_not_found"]);
        exit;
    }

    $ins = $pdo->prepare("
        INSERT INTO matches (worker_id, company_id, matched_by, matched_for, created_at)
        VALUES (?, ?, ?, ?, NOW())
    ");
    $ins->execute([$workerId, $companyId, $userId, $matchedFor]);

    echo json_encode(["success" => true, "match_id" => (int)$pdo->lastInsertId()]);
    exit;
}

if ($method === "PUT") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_supported"]);
    exit;
}

$globalMode = (int)($_GET["global"] ?? 0) === 1;
$where = " WHERE 1=1 ";
$params = [];

if (!$globalMode) {
    if ($roleId === 1 || $roleId === 5) {
        // admin/moderator: all
    } elseif ($roleId === 4) {
        $where .= " AND (m.company_id = ? OR m.matched_for = ? OR m.matched_by = ?) ";
        $params[] = $userId;
        $params[] = $userId;
        $params[] = $userId;
    } elseif ($roleId === 3) {
        $where .= " AND (m.matched_for = ? OR m.matched_by = ?) ";
        $params[] = $userId;
        $params[] = $userId;
    } elseif ($roleId === 2) {
        $where .= " AND w.user_id = ? ";
        $params[] = $userId;
    } else {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "forbidden"]);
        exit;
    }
}

$requestedCompanyId = (int)($_GET["company_id"] ?? 0);
if ($requestedCompanyId > 0) {
    if (!in_array($roleId, [1, 5], true) && $requestedCompanyId !== $userId) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "forbidden_company_scope"]);
        exit;
    }
    $where .= " AND m.company_id = ? ";
    $params[] = $requestedCompanyId;
}

$stmt = $pdo->prepare("
    SELECT
        m.id,
        m.worker_id,
        m.company_id,
        m.matched_by,
        m.matched_for,
        m.created_at,
        w.first_name,
        w.last_name,
        w.user_id AS worker_user_id,
        c.email AS company_email,
        c.company_name AS company_name,
        mb.email AS matched_by_email,
        mb.company_name AS matched_by_company_name,
        mb.agency_name AS matched_by_agency_name,
        mf.email AS matched_for_email,
        mf.company_name AS matched_for_company_name,
        mf.agency_name AS matched_for_agency_name
    FROM matches m
    LEFT JOIN workers w ON w.id = m.worker_id
    LEFT JOIN users c ON c.id = m.company_id
    LEFT JOIN users mb ON mb.id = m.matched_by
    LEFT JOIN users mf ON mf.id = m.matched_for
    $where
    ORDER BY m.id DESC
");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$data = [];
foreach ($rows as $row) {
    $workerName = trim(((string)($row["first_name"] ?? "")) . " " . ((string)($row["last_name"] ?? "")));
    if ($workerName === "") {
        $workerName = "Worker #" . (int)($row["worker_id"] ?? 0);
    }

    $companyName = trim((string)($row["company_name"] ?? ""));
    if ($companyName === "") {
        $companyName = trim((string)($row["company_email"] ?? ""));
    }
    if ($companyName === "") {
        $companyName = "Company #" . (int)($row["company_id"] ?? 0);
    }

    $matchedByName = trim((string)($row["matched_by_company_name"] ?? ""));
    if ($matchedByName === "") $matchedByName = trim((string)($row["matched_by_agency_name"] ?? ""));
    if ($matchedByName === "") $matchedByName = trim((string)($row["matched_by_email"] ?? ""));
    if ($matchedByName === "") $matchedByName = "User #" . (int)($row["matched_by"] ?? 0);

    $matchedForName = trim((string)($row["matched_for_company_name"] ?? ""));
    if ($matchedForName === "") $matchedForName = trim((string)($row["matched_for_agency_name"] ?? ""));
    if ($matchedForName === "") $matchedForName = trim((string)($row["matched_for_email"] ?? ""));
    if ($matchedForName === "") $matchedForName = "User #" . (int)($row["matched_for"] ?? 0);

    $row["worker_name"] = $workerName;
    $row["company_name_full"] = $companyName;
    $row["matched_by_name"] = $matchedByName;
    $row["matched_for_name"] = $matchedForName;

    $data[] = $row;
}

echo json_encode(["success" => true, "data" => $data]);
?>
