<?php

declare(strict_types=1);

namespace App\Models;

class EventUser extends BaseModel
{
    protected string $table = 'event_users';
    protected string $primaryKey = 'id';

    public function attachUser(int $eventId, int $userId): void
    {
        $exists = $this->queryOne(
            "SELECT 1 FROM {$this->table} WHERE event_id = :eid AND user_id = :uid",
            ['eid' => $eventId, 'uid' => $userId]
        );

        if (!$exists) {
            $this->execute(
                "INSERT INTO {$this->table} (event_id, user_id) VALUES (:eid, :uid)",
                ['eid' => $eventId, 'uid' => $userId]
            );
        }
    }

    public function detachUser(int $eventId, int $userId): void
    {
        $this->execute(
            "DELETE FROM {$this->table} WHERE event_id = :eid AND user_id = :uid",
            ['eid' => $eventId, 'uid' => $userId]
        );
    }

    public function getUserEvents(int $userId): array
    {
        return $this->query(
            "SELECT e.* FROM events e
             INNER JOIN {$this->table} eu ON e.id = eu.event_id
             WHERE eu.user_id = :uid AND e.status = 'active'
             ORDER BY e.start_date DESC
             LIMIT 100",
            ['uid' => $userId]
        );
    }

    public function getEventUsers(int $eventId): array
    {
        return $this->query(
            "SELECT u.id, u.name, u.email, u.role, u.status
             FROM users u
             INNER JOIN {$this->table} eu ON u.id = eu.user_id
             WHERE eu.event_id = :eid
             ORDER BY u.name
             LIMIT 500",
            ['eid' => $eventId]
        );
    }

    public function syncUsers(int $eventId, array $userIds): void
    {
        $this->beginTransaction();
        try {
            $this->execute(
                "DELETE FROM {$this->table} WHERE event_id = :eid",
                ['eid' => $eventId]
            );

            if (!empty($userIds)) {
                $placeholders = [];
                $params = [];
                foreach ($userIds as $i => $uid) {
                    $ek = "eid{$i}";
                    $uk = "uid{$i}";
                    $placeholders[] = "(:{$ek}, :{$uk})";
                    $params[$ek] = $eventId;
                    $params[$uk] = (int) $uid;
                }
                $sql = "INSERT INTO {$this->table} (event_id, user_id) VALUES " . implode(',', $placeholders);
                $stmt = $this->db->prepare($sql);
                $stmt->execute($params);
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
    }

    public function removeAllUsers(int $eventId): void
    {
        $this->execute(
            "DELETE FROM {$this->table} WHERE event_id = :eid",
            ['eid' => $eventId]
        );
    }
}
