<?php

/**
 * Tenant-Aware Contract Model
 * Each workspace has completely isolated contract data
 */
class TenantContract {
    
    /**
     * Get all contracts for current tenant
     */
    public static function getAll(): array {
        return TenantDB::query("SELECT * FROM contracts ORDER BY created_at DESC");
    }
    
    /**
     * Get contract by ID for current tenant
     */
    public static function getById(int $id): ?array {
        $result = TenantDB::query("SELECT * FROM contracts WHERE id = ?", [$id], true);
        return $result ?: null;
    }
    
    /**
     * Create new contract for current tenant
     */
    public static function create(array $data): int {
        // Auto-generate contract number for this tenant
        $data['contract_number'] = 'CTR-' . TenantDB::getNextSequence('contract');
        
        return TenantDB::insert('contracts', $data);
    }
    
    /**
     * Update contract for current tenant
     */
    public static function update(int $id, array $data): bool {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            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 contracts SET " . implode(', ', $setParts) . " WHERE id = ? AND company_id = ?";
        
        try {
            $stmt = $pdo->prepare($query);
            return $stmt->execute($values);
        } catch (PDOException $e) {
            error_log("TenantContract Update Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete contract 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 contracts WHERE id = ? AND company_id = ?");
            return $stmt->execute([$id, $companyId]);
        } catch (PDOException $e) {
            error_log("TenantContract Delete Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get contract file path for current tenant
     */
    public static function getFilePath(int $contractId, string $filename = ''): string {
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            throw new Exception("No tenant context set");
        }
        
        $baseDir = __DIR__ . "/../storage/companies/$companyId/contracts/";
        
        if (!is_dir($baseDir)) {
            mkdir($baseDir, 0755, true);
        }
        
        return $baseDir . ($filename ? $filename : "contract_$contractId.pdf");
    }
    
    /**
     * Generate contract PDF for current tenant
     */
    public static function generatePDF(int $contractId, string $content): string {
        $filePath = self::getFilePath($contractId);
        
        // Simple PDF generation (you can replace with proper library)
        $pdfContent = "%PDF-1.4\n%âãÏÓ\n1 0 obj\n<<\n/Type /Catalog\n/Pages 2 0 R\n>>\nendobj\n2 0 obj\n<<\n/Type /Pages\n/Kids [3 0 R]\n/Count 1\n>>\nendobj\n3 0 obj\n<<\n/Type /Page\n/Parent 2 0 R\n/MediaBox [0 0 612 792]\n/Contents 4 0 R\n>>\nendobj\n4 0 obj\n<<\n/Length " . strlen($content) . "\n>>\nstream\n" . $content . "\nendstream\nendobj\nxref\n0 5\n0000000000 65535 f\n0000000010 00000 n\n0000000079 00000 n\n0000000173 00000 n\n0000000301 00000 n\ntrailer\n<<\n/Size 5\n/Root 1 0 R\n>>\nstartxref\n" . (strlen($content) + 100) . "\n%%EOF";
        
        file_put_contents($filePath, $pdfContent);
        
        return $filePath;
    }
    
    /**
     * Search contracts for current tenant
     */
    public static function search(string $term): array {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return [];
        }
        
        try {
            $stmt = $pdo->prepare("
                SELECT c.*, cl.name as client_name FROM contracts c
                LEFT JOIN clients cl ON c.client_id = cl.id
                WHERE c.company_id = ? AND (
                    c.contract_number LIKE ? OR 
                    c.title LIKE ? OR 
                    c.status LIKE ? OR 
                    cl.name LIKE ?
                ) 
                ORDER BY c.created_at DESC
            ");
            $stmt->execute([$companyId, "%$term%", "%$term%", "%$term%", "%$term%"]);
            return $stmt->fetchAll() ?: [];
        } catch (PDOException $e) {
            error_log("TenantContract Search Error: " . $e->getMessage());
            return [];
        }
    }
}
