<?php

namespace App\Services;

use App\Core\Database;
use PDO;

class TrackChairScope
{
    public static function isTrackChair(): bool
    {
        return (
    ($_SESSION['conference_role'] ?? $_SESSION['role'] ?? '')
    === 'track_chair'
);
    }

    public static function conferenceId(): int
    {
        $cid = (int)(
            $_SESSION['conference_id']
            ??
            $_SESSION['current_conference_id']
            ??
            0
        );

        if (
            !$cid &&
            function_exists('default_conference_id')
        ) {
            $cid = (int) default_conference_id();
        }

        return $cid;
    }

    public static function trackIds(): array
    {
        if (!self::isTrackChair()) {
            return [];
        }

        $db = Database::getInstance();

        $uid = (int)($_SESSION['user_id'] ?? 0);
        $cid = self::conferenceId();

        if (!$uid || !$cid) {
            return [];
        }

        $ids = [];

        try {

            $st = $db->prepare("
                SELECT track_id
                FROM track_chair_assignments
                WHERE conference_id = ?
                AND user_id = ?
                AND is_active = 1
            ");

            $st->execute([$cid,$uid]);

            $tmpRows =
                $st->fetchAll(PDO::FETCH_COLUMN);

            error_log(
                'TRACK_IDS_SQL ' .
                json_encode([
                    'uid'=>$uid,
                    'cid'=>$cid,
                    'rows'=>$tmpRows
                ])
            );

            $ids = array_merge(
                $ids,
                $tmpRows
            );

        } catch (\Throwable $e) {}

        try {

            $st = $db->prepare("
                SELECT id
                FROM tracks
                WHERE conference_id = ?
                AND chair_user_id = ?
            ");

            $st->execute([$cid,$uid]);

            $ids = array_merge(
                $ids,
                $st->fetchAll(PDO::FETCH_COLUMN)
            );

        } catch (\Throwable $e) {}

        return array_values(
            array_unique(
                array_map('intval',$ids)
            )
        );
    }

    public static function sql(string $alias='s'): array
    {
        if (!self::isTrackChair()) {
            return ['',[]];
        }

        $tracks = self::trackIds();

        if (!$tracks) {
            return [' AND 1=0 ',[]];
        }

        $in = implode(',', array_fill(0,count($tracks),'?'));

        return [
            " AND {$alias}.track_id IN ($in) ",
            $tracks
        ];
    }
}
