<?php
// src/Models/Tenant.php
namespace App\Models;

use App\Database\DatabaseManager;
use PDO;

class Tenant
{
    private $db;

    public function __construct()
    {
        $this->db = DatabaseManager::connect();
    }

    public function findById(string $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM tenants WHERE id = :id');
        $stmt->bindParam(':id', $id);
        $stmt->execute();

        return $stmt->fetch() ?: null;
    }

    public function findBySubdomain(string $subdomain): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM tenants WHERE subdomain = :subdomain');
        $stmt->bindParam(':subdomain', $subdomain);
        $stmt->execute();

        return $stmt->fetch() ?: null;
    }

    public function create(array $data): string
    {
        $id = bin2hex(random_bytes(16)); // Simple ID generation for demo
        $stmt = $this->db->prepare('
            INSERT INTO tenants (id, name, subdomain) 
            VALUES (:id, :name, :subdomain)
            RETURNING id
        ');
        $stmt->bindParam(':id', $id);
        $stmt->bindParam(':name', $data['name']);
        $stmt->bindParam(':subdomain', $data['subdomain']);
        $stmt->execute();

        $result = $stmt->fetch();
        return $result['id'];
    }
}