<?php
class TenantModel {
    public static function create(array $data): int {
        $cols = implode(',', array_map(fn($c) => "`{$c}`", array_keys($data)));
        $vals = implode(',', array_fill(0, count($data), '?'));
        $stmt = db()->prepare("INSERT INTO tenants ({$cols}) VALUES ({$vals})");
        $stmt->execute(array_values($data));
        return (int)db()->lastInsertId();
    }

    public static function findById(int $id): ?array {
        $stmt = db()->prepare("SELECT * FROM tenants WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public static function findBySlug(string $slug): ?array {
        $stmt = db()->prepare("SELECT * FROM tenants WHERE slug = ? LIMIT 1");
        $stmt->execute([$slug]);
        return $stmt->fetch() ?: null;
    }

    public static function findByEmail(string $email): ?array {
        $stmt = db()->prepare("SELECT * FROM tenants WHERE business_email = ? LIMIT 1");
        $stmt->execute([$email]);
        return $stmt->fetch() ?: null;
    }

    public static function update(int $id, array $data): bool {
        $sets = implode(',', array_map(fn($c) => "`{$c}` = ?", array_keys($data)));
        $stmt = db()->prepare("UPDATE tenants SET {$sets} WHERE id = ?");
        return $stmt->execute([...array_values($data), $id]);
    }

    public static function all(string $order = 'created_at DESC', int $limit = 0, int $offset = 0): array {
        $sql = "SELECT t.*, s.status as sub_status, p.name as plan_name
                FROM tenants t
                LEFT JOIN subscriptions s ON s.tenant_id = t.id AND s.status = 'active'
                LEFT JOIN plans p ON p.id = s.plan_id
                ORDER BY {$order}";
        if ($limit) $sql .= " LIMIT {$limit} OFFSET {$offset}";
        return db()->query($sql)->fetchAll();
    }

    public static function count(): int {
        return (int)db()->query("SELECT COUNT(*) FROM tenants")->fetchColumn();
    }

    public static function stats(): array {
        $row = db()->query("
            SELECT
                COUNT(*) as total,
                SUM(status='active') as active,
                SUM(status='trial') as trial,
                SUM(status='suspended') as suspended
            FROM tenants
        ")->fetch();
        return $row;
    }

    public static function seed(int $tenantId, int $locationId): void {
        // Initialize modern RBAC roles & permissions
        if (class_exists('Role')) {
            Role::createDefaultRoles($tenantId);
            Role::assignDefaultPermissions($tenantId);
        }

        // Default units
        $units = [
            ['Piece','PCS','Individual items'],
            ['Kilogram','KG','Weight measurement'],
            ['Gram','G','Small weight measurement'],
            ['Liter','L','Volume measurement'],
            ['Milliliter','ML','Small volume measurement'],
            ['Box','BOX','Packaged items'],
            ['Carton','CTN','Larger packaged items'],
            ['Dozen','DOZ','12 items'],
            ['Meter','M','Length measurement'],
            ['Pair','PR','2 items']
        ];
        foreach ($units as $unit) {
            db()->prepare("INSERT INTO units (tenant_id,name,abbreviation,description) VALUES (?,?,?,?)")
                ->execute([$tenantId,$unit[0],$unit[1],$unit[2]]);
        }

        // Default tax groups
        $taxes = [
            ['No Tax',0,'No tax applied'],
            ['VAT Standard',15,'Standard VAT rate'],
            ['VAT Reduced',5,'Reduced VAT rate'],
            ['Service Tax',10,'Service tax rate']
        ];
        foreach ($taxes as $tax) {
            db()->prepare("INSERT INTO tax_groups (tenant_id,name,rate,description) VALUES (?,?,?,?)")
                ->execute([$tenantId,$tax[0],$tax[1],$tax[2]]);
        }

        // Default brand
        db()->prepare("INSERT INTO brands (tenant_id,name) VALUES (?,?)")->execute([$tenantId,'Generic']);

        // Walk-in customer
        db()->prepare("INSERT INTO customers (tenant_id,name,phone) VALUES (?,?,?)")->execute([$tenantId,'Walk-in Customer','N/A']);

        // Default settings
        $defaults = [
            'currency'=>'GHS','currency_symbol'=>'GH₵','currency_position'=>'before',
            'default_location'=>$locationId,'tax_rate'=>'0','low_stock_threshold'=>'10',
            'expiry_alert_days'=>'30','enable_batch_tracking'=>'0','enable_serial_tracking'=>'0',
            'default_payment_method'=>'cash','default_discount_type'=>'fixed',
            'require_customer_for_sales'=>'0','receipt_header'=>'Thank you for shopping with us!',
            'receipt_footer'=>'Please come again!','auto_print_receipt'=>'0',
            'enable_notifications'=>'1','sale_prefix'=>'INV','purchase_prefix'=>'PUR',
            'transfer_prefix'=>'TRF','adjustment_prefix'=>'ADJ',
            'date_format'=>'Y-m-d','backup_frequency'=>'manual',
        ];
        foreach ($defaults as $k => $v) {
            db()->prepare("INSERT INTO settings (tenant_id,setting_key,setting_value) VALUES (?,?,?)")
                 ->execute([$tenantId,$k,$v]);
        }
    }
}
