<?php

/**
 * Tenant-Aware Client Model
 * Each workspace has completely isolated client data
 */
class TenantClient {
    
    /**
     * Get all clients for current tenant
     */
    public static function getAll(): array {
        return TenantDB::query("SELECT * FROM clients ORDER BY created_at DESC");
    }
    
    /**
     * Get client by ID for current tenant
     */
    public static function getById(int $id): ?array {
        $result = TenantDB::query("SELECT * FROM clients WHERE id = ?", [$id], true);
        return $result ?: null;
    }
    
    /**
     * Create new client for current tenant
     */
    public static function create(array $data): int {
        // Auto-generate client number for this tenant
        $data['client_number'] = 'CLI-' . TenantDB::getNextSequence('client');
        
        // Use current company ID from workspace if available, fallback to tenant context
        $companyId = null;
        
        // Try to get company ID from workspace parameter
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $pdo = getPDO();
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            throw new Exception("No company context available");
        }
        
        $data['company_id'] = $companyId;
        $data['created_at'] = date('Y-m-d H:i:s');
        
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));
        
        $pdo = getPDO();
        $query = "INSERT INTO clients ($columns) VALUES ($placeholders)";
        
        try {
            $stmt = $pdo->prepare($query);
            $stmt->execute(array_values($data));
            return (int) $pdo->lastInsertId();
        } catch (PDOException $e) {
            error_log("TenantClient Create Error: " . $e->getMessage());
            throw new Exception("Failed to insert data");
        }
    }
    
    /**
     * Update client for current tenant
     */
    public static function update(int $id, array $data): bool {
        $pdo = getPDO();
        
        // Use current company ID from workspace if available, fallback to tenant context
        $companyId = null;
        
        // Try to get company ID from workspace parameter
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            error_log("TenantClient Update Error: No company context available");
            return false;
        }
        
        $data['updated_at'] = date('Y-m-d H:i:s');
        
        $setParts = [];
        $values = [];
        
        foreach ($data as $key => $value) {
            $setParts[] = "$key = ?";
            $values[] = $value;
        }
        
        $values[] = $id;
        $values[] = $companyId;
        
        $query = "UPDATE clients SET " . implode(', ', $setParts) . " WHERE id = ? AND company_id = ?";
        
        error_log("TenantClient Update: Query = $query");
        error_log("TenantClient Update: Values = " . json_encode($values));
        
        try {
            $stmt = $pdo->prepare($query);
            $result = $stmt->execute($values);
            error_log("TenantClient Update: Result = " . ($result ? 'success' : 'failed'));
            return $result;
        } catch (PDOException $e) {
            error_log("TenantClient Update Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete client for current tenant
     */
    public static function delete(int $id): bool {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return false;
        }
        
        try {
            $stmt = $pdo->prepare("DELETE FROM clients WHERE id = ? AND company_id = ?");
            return $stmt->execute([$id, $companyId]);
        } catch (PDOException $e) {
            error_log("TenantClient Delete Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Search clients for current tenant
     */
    public static function search(string $term): array {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return [];
        }
        
        try {
            $stmt = $pdo->prepare("
                SELECT * FROM clients 
                WHERE company_id = ? AND (
                    name LIKE ? OR 
                    email LIKE ? OR 
                    company LIKE ?
                ) 
                ORDER BY name ASC
            ");
            $stmt->execute([$companyId, "%$term%", "%$term%", "%$term%"]);
            return $stmt->fetchAll() ?: [];
        } catch (PDOException $e) {
            error_log("TenantClient Search Error: " . $e->getMessage());
            return [];
        }
    }
}
