<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use PDO;

class AdminTrackChairController extends Controller
{
    private function role(): string
    {
        return (string)(
            $_SESSION['role']
            ?? $_SESSION['role_code']
            ?? $_SESSION['conference_role']
            ?? $_SESSION['user_role']
            ?? ''
        );
    }

    private function guard(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (!in_array($this->role(), ['superadmin','super_admin','admin','org_admin','organizer','conference_chair'], true)) {
            http_response_code(403);
            die("Access denied.");
        }
    }

    public function index(): void
    {
        $this->guard();

        $db = Database::getInstance();

        $conferenceId = (int)(
            $_GET['conference_id']
            ?? $_SESSION['conference_id']
            ?? $_SESSION['current_conference_id']
            ?? 0
        );

        $conferences = $db->query("
            SELECT
                id,
                COALESCE(title_en,title_ar,CONCAT('Conference #',id)) AS title
            FROM conferences
            ORDER BY id DESC
        ")->fetchAll(PDO::FETCH_ASSOC);

        if ($conferenceId <= 0 && $conferences) {
            $conferenceId = (int)$conferences[0]['id'];
        }

        $_SESSION['conference_id'] = $conferenceId;
        $_SESSION['current_conference_id'] = $conferenceId;

        $tracksStmt = $db->prepare("
            SELECT
                id,
                conference_id,
                COALESCE(name_en,name_ar,CONCAT('Track #',id)) AS name,
                chair_user_id,
                COALESCE(is_active,1) AS is_active
            FROM tracks
            WHERE conference_id = ?
            ORDER BY sort_order ASC, id ASC
        ");
        $tracksStmt->execute([$conferenceId]);
        $tracks = $tracksStmt->fetchAll(PDO::FETCH_ASSOC);

        /*
        Only show users who are already track_chair/conference_chair/reviewer
        in this conference. Fallback to all active users if conference_user_roles
        is incomplete.
        */
        $users = [];


        try {

            $usersStmt = $db->prepare("
                SELECT DISTINCT
                    u.id,

                    COALESCE(
                        NULLIF(
                            TRIM(
                                CONCAT(
                                    COALESCE(u.first_name,''),
                                    ' ',
                                    COALESCE(u.last_name,'')
                                )
                            ),
                            ''
                        ),
                        u.email,
                        CONCAT('User #',u.id)
                    ) AS name,

                    u.email

                FROM conference_user_roles cur

                INNER JOIN users u
                    ON u.id = cur.user_id

                WHERE cur.conference_id = ?

                  AND COALESCE(u.is_active,1)=1

                  AND u.id NOT IN
                  (
                      SELECT DISTINCT a.user_id
                      FROM track_chair_assignments a
                      WHERE a.conference_id = cur.conference_id
                        AND a.is_active = 1
                  )

                ORDER BY name ASC
            ");

            $usersStmt->execute([
                $conferenceId
            ]);

            $users =
                $usersStmt->fetchAll(PDO::FETCH_ASSOC);

        } catch (\Throwable $e) {

            $users = [];

        }

        $assignedStmt = $db->prepare("
            SELECT
                a.*,
                COALESCE(t.name_en,t.name_ar,CONCAT('Track #',t.id)) AS track_name,
                COALESCE(NULLIF(CONCAT(u.first_name,' ',u.last_name),''), u.email, CONCAT('User #',u.id)) AS user_name,
                u.email,
                COALESCE(NULLIF(CONCAT(byu.first_name,' ',byu.last_name),''), byu.email, '') AS assigned_by_name
            FROM track_chair_assignments a
            JOIN tracks t
                ON t.id = a.track_id
            JOIN users u
                ON u.id = a.user_id
            LEFT JOIN users byu
                ON byu.id = a.assigned_by
            WHERE a.conference_id = ?
            ORDER BY t.id ASC, user_name ASC
        ");
        $assignedStmt->execute([$conferenceId]);
        $assignments = $assignedStmt->fetchAll(PDO::FETCH_ASSOC);

        ob_start();
        require BASE_PATH . '/app/views/admin/track_chairs/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }

    public function store(): void
    {
        $this->guard();

        $db = Database::getInstance();

        $conferenceId = (int)($_POST['conference_id'] ?? 0);
        $trackIds = $_POST['track_ids'] ?? [];
        $userId = (int)($_POST['user_id'] ?? 0);
        $assignedBy = (int)($_SESSION['user_id'] ?? 0);

        if ($conferenceId <= 0 || $userId <= 0 || !is_array($trackIds) || !$trackIds) {
            header("Location: /easychair/admin/track-chairs?conference_id=".$conferenceId);
            exit;
        }

        $insert = $db->prepare("
            INSERT INTO track_chair_assignments
            (
                conference_id,
                track_id,
                user_id,
                assigned_by,
                is_active
            )
            VALUES
            (?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
                is_active = 1,
                assigned_by = VALUES(assigned_by),
                updated_at = CURRENT_TIMESTAMP
        ");

        $syncLegacy = $db->prepare("
            UPDATE tracks
            SET chair_user_id = ?
            WHERE id = ?
              AND conference_id = ?
              AND (
                    chair_user_id IS NULL
                    OR chair_user_id = 0
                    OR chair_user_id = ?
                  )
        ");

        foreach ($trackIds as $trackId) {
            $trackId = (int)$trackId;

            if ($trackId <= 0) {
                continue;
            }

            $insert->execute([
                $conferenceId,
                $trackId,
                $userId,
                $assignedBy
            ]);

            /*
             * Auto-create conference membership
             * for Track Chair.
             */
            try {

                $roleId =
                    (int)$db->query("
                        SELECT id
                        FROM roles
                        WHERE code='track_chair'
                        LIMIT 1
                    ")->fetchColumn();

                if ($roleId > 0) {

                    $db->prepare("
                        INSERT IGNORE INTO user_conferences
                        (
                            user_id,
                            conference_id,
                            role_id
                        )
                        VALUES
                        (?, ?, ?)
                    ")->execute([
                        $userId,
                        $conferenceId,
                        $roleId
                    ]);

                }

            } catch (\Throwable $e) {}

            try {

                $db->prepare("
                    INSERT IGNORE INTO conference_user_roles
                    (
                        user_id,
                        conference_id,
                        role_code
                    )
                    VALUES
                    (?, ?, 'track_chair')
                ")->execute([
                    $userId,
                    $conferenceId
                ]);

            } catch (\Throwable $e) {}

            /*
            Backward compatibility:
            only fill tracks.chair_user_id if empty or already same user.
            This avoids overwriting existing mature single-chair logic.
            */
            $syncLegacy->execute([
                $userId,
                $trackId,
                $conferenceId,
                $userId
            ]);
        }

        /*
        --------------------------------------------------
        Track Chair Email Notification
        --------------------------------------------------
        */
        /*
--------------------------------------------------
PACK818D
Track Chair Email Queue
--------------------------------------------------
*/

try {

    $trackNames = [];

    if (!empty($trackIds)) {

        $ph = implode(
            ',',
            array_fill(
                0,
                count($trackIds),
                '?'
            )
        );

        $st = $db->prepare("
            SELECT
                COALESCE(
                    name_en,
                    name_ar,
                    CONCAT('Track #',id)
                ) AS track_name
            FROM tracks
            WHERE id IN ($ph)
            ORDER BY id
        ");

        $st->execute($trackIds);

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

    $u = $db->prepare("
        SELECT
            first_name,
            last_name,
            email,
            preferred_lang
        FROM users
        WHERE id = ?
        LIMIT 1
    ");

    $u->execute([$userId]);

    $user =
        $u->fetch(PDO::FETCH_ASSOC);

    $c = $db->prepare("
        SELECT
            COALESCE(
                title_en,
                title_ar,
                CONCAT('Conference #',id)
            ) AS conference_title
        FROM conferences
        WHERE id = ?
        LIMIT 1
    ");

    $c->execute([$conferenceId]);

    $conferenceTitle =
        (string)(
            $c->fetchColumn()
            ?: ''
        );

    if (!empty($user['email'])) {

        \App\Services\SubmissionWorkflowService::queueEmail(

            $conferenceId,

            'track_chair_assigned',

            $user['email'],

            trim(
                ($user['first_name'] ?? '')
                . ' '
                .
                ($user['last_name'] ?? '')
            ),

            [

                'recipient_name' =>
                    trim(
                        ($user['first_name'] ?? '')
                        . ' '
                        .
                        ($user['last_name'] ?? '')
                    ),

   'track_chair_email' =>
    $user['email'],

                'conference_title' =>
                    $conferenceTitle,

                'track_names' =>
                    implode(
                        ', ',
                        $trackNames
                    ),

                'dashboard_url' =>
                    'https://www.jpu.edu.jo/easychair/admin/dashboard'

            ],

            null,

            $userId,

            $user['preferred_lang'] ?? 'en'
        );

        error_log(
            'TRACK_CHAIR_EMAIL_QUEUED: '
            . $user['email']
        );
    }

} catch (\Throwable $e) {

    error_log(
        'TRACK_CHAIR_EMAIL_ERROR: '
        . $e->getMessage()
    );

}

        header("Location: /easychair/admin/track-chairs?conference_id=".$conferenceId);
        exit;
    }

    public function toggle(): void
    {
        $this->guard();

        $id = (int)($_POST['id'] ?? 0);
        $conferenceId = (int)($_POST['conference_id'] ?? $_SESSION['conference_id'] ?? 0);

        if ($id > 0) {
            $db = Database::getInstance();

            $stmt = $db->prepare("
                SELECT *
                FROM track_chair_assignments
                WHERE id = ?
                LIMIT 1
            ");
            $stmt->execute([$id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($row) {
                $newStatus = ((int)$row['is_active'] === 1) ? 0 : 1;

                $db->prepare("
                    UPDATE track_chair_assignments
                    SET is_active = ?
                    WHERE id = ?
                ")->execute([$newStatus, $id]);

                /*
                If disabled and legacy chair_user_id equals this user, clear it.
                If enabled and legacy chair_user_id empty, restore it.
                */
                if ($newStatus === 0) {
                    $db->prepare("
                        UPDATE tracks
                        SET chair_user_id = NULL
                        WHERE id = ?
                          AND conference_id = ?
                          AND chair_user_id = ?
                    ")->execute([
                        (int)$row['track_id'],
                        (int)$row['conference_id'],
                        (int)$row['user_id']
                    ]);
                } else {
                    $db->prepare("
                        UPDATE tracks
                        SET chair_user_id = ?
                        WHERE id = ?
                          AND conference_id = ?
                          AND (chair_user_id IS NULL OR chair_user_id = 0)
                    ")->execute([
                        (int)$row['user_id'],
                        (int)$row['track_id'],
                        (int)$row['conference_id']
                    ]);
                }
            }
        }

        header("Location: /easychair/admin/track-chairs?conference_id=".$conferenceId);
        exit;
    }
}
