<?php

/**
 * Tenant-Aware Proposal Model
 * Each workspace has completely isolated proposal data
 */
class TenantProposal {
    
    /**
     * Get all proposals for current tenant
     */
    public static function getAll(): array {
        return TenantDB::query("SELECT * FROM proposals ORDER BY created_at DESC");
    }
    
    /**
     * Get proposal by ID for current tenant
     */
    public static function getById(int $id): ?array {
        $result = TenantDB::query("SELECT * FROM proposals WHERE id = ?", [$id], true);
        return $result ?: null;
    }
    
    /**
     * Create new proposal for current tenant
     */
    public static function create(array $data): int {
        // Auto-generate proposal number for this tenant
        $data['proposal_number'] = 'PRO-' . TenantDB::getNextSequence('proposal');
        
        return TenantDB::insert('proposals', $data);
    }
    
    /**
     * Update proposal 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 proposals SET " . implode(', ', $setParts) . " WHERE id = ? AND company_id = ?";
        
        try {
            $stmt = $pdo->prepare($query);
            return $stmt->execute($values);
        } catch (PDOException $e) {
            error_log("TenantProposal Update Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete proposal 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 proposals WHERE id = ? AND company_id = ?");
            return $stmt->execute([$id, $companyId]);
        } catch (PDOException $e) {
            error_log("TenantProposal Delete Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get proposal file path for current tenant
     */
    public static function getFilePath(int $proposalId, string $filename = ''): string {
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            throw new Exception("No tenant context set");
        }
        
        $baseDir = __DIR__ . "/../storage/companies/$companyId/proposals/";
        
        if (!is_dir($baseDir)) {
            mkdir($baseDir, 0755, true);
        }
        
        return $baseDir . ($filename ? $filename : "proposal_$proposalId.pdf");
    }
    
    /**
     * Generate proposal PDF for current tenant
     */
    public static function generatePDF(int $proposalId, string $content): string {
        $filePath = self::getFilePath($proposalId);
        
        // 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 proposals for current tenant
     */
    public static function search(string $term): array {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return [];
        }
        
        try {
            $stmt = $pdo->prepare("
                SELECT p.*, c.name as client_name FROM proposals p
                LEFT JOIN clients c ON p.client_id = c.id
                WHERE p.company_id = ? AND (
                    p.proposal_number LIKE ? OR 
                    p.title LIKE ? OR 
                    p.status LIKE ? OR 
                    c.name LIKE ?
                ) 
                ORDER BY p.created_at DESC
            ");
            $stmt->execute([$companyId, "%$term%", "%$term%", "%$term%", "%$term%"]);
            return $stmt->fetchAll() ?: [];
        } catch (PDOException $e) {
            error_log("TenantProposal Search Error: " . $e->getMessage());
            return [];
        }
    }
}
