<?php
defined('BASEPATH') or exit('No direct script access allowed');

class User_model extends CI_Model
{
    protected $collection = 'Users';

    public function __construct()
    {
        parent::__construct();
        $this->load->library('firebase');
    }

    public function getAllUsers()
    {
        $docs = $this->firebase->getCollection($this->collection);
        $users = [];

        foreach ($docs as $id => $data) {
            $data['id'] = $id;
            $data['status'] = $data['status'] ?? 'Inactive';
            $users[] = $data;
        }
        // Sort by userDate (latest first)
        usort($users, function ($a, $b) {
            return ($b['userDate'] ?? 0) <=> ($a['userDate'] ?? 0);
        });

        return $users;
    }

    public function UserForDashboard()
    {
        $docs = $this->firebase->getCollection($this->collection);
        $users = [];

        foreach ($docs as $id => $data) {
            $data['id'] = $id;
            $data['status'] = $data['status'] ?? 'Inactive';
            $data['userDate'] = isset($data['userDate']) ? (int)$data['userDate'] : 0; // ensure timestamp
            $users[] = $data;
        }

        // Sort users by userDate descending (newest first)
        usort($users, function ($a, $b) {
            return $b['userDate'] <=> $a['userDate'];
        });

        // Return top 5
        return array_slice($users, 0, 5);
    }


    public function toggleUserStatus($id)
    {
        $user = $this->firebase->getDocument($this->collection, $id);
        if (!$user)
            return false;

        $newStatus = ($user['status'] ?? 'Inactive') === 'Active' ? 'Inactive' : 'Active';

        return $this->firebase->updateDocument($this->collection, $id, [
            'status' => $newStatus,
            'updated_at' => round(microtime(true) * 1000)
        ]);
    }
    public function getUsersByIds($ids = [])
    {
        if (empty($ids)) return [];

        $docs = $this->firebase->getCollection($this->collection);
        $users = [];

        foreach ($docs as $id => $data) {
            if (in_array($id, $ids)) {
                $data['id'] = $id;
                $data['status'] = $data['status'] ?? 'Inactive';
                $users[] = $data;
            }
        }

        return $users;
    }
    public function getAllUserIds()
    {
        $docs = $this->firebase->getCollection($this->collection);
        $userIds = [];

        foreach ($docs as $id => $data) {
            $userIds[] = $id;
        }

        return $userIds;
    }
}
