<?php
$email = 'info@ultratrailfjord.com';

$liste = jira_get_tickets_by_email($email);

if ($liste['success']) {
    foreach ($liste['tickets'] as $ticket) {
        echo '<a href="' . $ticket['url'] . '" target="_blank">' . $ticket['key'] . ' - ' . $ticket['summary'] . ' (' . $ticket['status'] . ')</a><br>';
    }
} else {
    echo 'Erreur : ' . $liste['message'];
}

/**
 * Recherche tous les tickets JIRA ouverts d’un utilisateur selon son courriel (ou accountId)
 * Compatible avec le nouvel endpoint /rest/api/3/search/jql
 */
function jira_get_tickets_by_email($email)
{
    $jiraDomain = 'https://progiwebinc.atlassian.net';
    $userEmail  = 'stephan@progiweb.ca';
    $apiToken   = 'ATATT3xFfGF0DuhOhRUxFlj2hFpLuzYGapJIrhMETB35NnLFi1TyxDszp3tTa8MaadTpT72GfDk9FOpDm07m6HbdXoQ9plDeRvB6OwRnD19VrIqA8M3HmDGgf_MWR7Pwk5731ahbgb4UBdRgj-ICBqt9A0SjJPnnoTfu4ECVh51HjM0RsekOmeM=908B030C';

    $projectKey = 'SM';

    // 1) Résoudre l'accountId à partir de l'email
    $accountId = jira_find_account_id_by_email($jiraDomain, $userEmail, $apiToken, $email);

    // 2) Construire le ou les JQL à tester (accountId en priorité)
    $jqls = [];
    if ($accountId) {
        $jqls[] = 'project = ' . $projectKey . ' AND reporter = ' . $accountId . ' ORDER BY created DESC';
    }
    $jqls[] = 'project = ' . $projectKey . ' AND reporter = "' . addslashes($email) . '" ORDER BY created DESC';

    // 3) Interroger le nouvel endpoint /rest/api/3/search/jql (POST)
    $headers = [
        'Authorization: Basic ' . base64_encode("$userEmail:$apiToken"),
        'Content-Type: application/json',
        'Accept: application/json'
    ];

    $fieldsWanted = ["summary","status"];
    $maxPerPage   = 100;
    $tickets      = [];
    $usedJql      = null;
    $lastErr      = null;

    foreach ($jqls as $jql) {
        $tickets = [];
        $usedJql = $jql;
        $nextPageToken = null;

        do {
            $payload = [
                "jql"        => $jql,
                "maxResults" => $maxPerPage,
                "fields"     => $fieldsWanted
            ];
            if ($nextPageToken) {
                $payload["nextPageToken"] = $nextPageToken;
            }

            $ch = curl_init($jiraDomain . '/rest/api/3/search/jql');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));

            $response = curl_exec($ch);
            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlErr  = curl_error($ch);
            curl_close($ch);

            if ($httpcode !== 200) {
                $lastErr = "HTTP $httpcode - " . ($response ?: $curlErr ?: 'Erreur inconnue');
                $tickets = [];
                break;
            }

            $data = json_decode($response, true);
            if (!isset($data['issues'])) {
                $lastErr = 'Réponse inattendue du service de recherche.';
                $tickets = [];
                break;
            }

            foreach ($data['issues'] as $issue) {
                $tickets[] = [
                    'key'     => $issue['key'],
                    'summary' => $issue['fields']['summary'] ?? '',
                    'status'  => $issue['fields']['status']['name'] ?? '',
                    'url'     => $jiraDomain . '/browse/' . $issue['key']
                ];
            }

            // pagination nouvelle API : token ou fin de résultats
            $nextPageToken = $data['nextPageToken'] ?? null;

        } while ($nextPageToken);

        if (!empty($tickets)) {
            break;
        }
    }

    if (!empty($tickets)) {
        return ['success' => true, 'tickets' => $tickets];
    }

    return [
        'success' => false,
        'message' => $lastErr ?: "Aucun ticket trouvé (JQL testé : $usedJql)"
    ];
}

/**
 * Recherche l’accountId d’un utilisateur à partir de son email.
 */
function jira_find_account_id_by_email($jiraDomain, $userEmail, $apiToken, $email)
{
    $headers = [
        'Authorization: Basic ' . base64_encode("$userEmail:$apiToken"),
        'Accept: application/json'
    ];
    $url = $jiraDomain . '/rest/api/3/user/search?query=' . urlencode($email);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpcode !== 200) {
        return null;
    }

    $users = json_decode($response, true);
    if (is_array($users) && count($users) > 0) {
        foreach ($users as $u) {
            if (!empty($u['emailAddress']) && strcasecmp($u['emailAddress'], $email) === 0) {
                return $u['accountId'] ?? null;
            }
        }
        return $users[0]['accountId'] ?? null;
    }

    return null;
}

/**
 * (Optionnel) Exemple pour lister les projets disponibles.
 */
function jira_get_projects()
{
    $jiraDomain = 'https://progiwebinc.atlassian.net';
    $userEmail  = 'stephan@progiweb.ca';
    $apiToken   = 'ATATT...';

    $ch = curl_init($jiraDomain . '/rest/api/3/project/search');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . base64_encode("$userEmail:$apiToken"),
        'Content-Type: application/json'
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}
