<?php

/**
 * Tenant-Aware Invoice Model
 * Each workspace has completely isolated invoice data
 */
class TenantInvoice {
    
    /**
     * Get all invoices for current tenant
     */
    public static function getAll(): array {
        return TenantDB::query("SELECT * FROM invoices ORDER BY created_at DESC");
    }
    
    /**
     * Get invoice by ID for current tenant
     */
    public static function getById(int $id): ?array {
        $result = TenantDB::query("SELECT * FROM invoices WHERE id = ?", [$id], true);
        return $result ?: null;
    }
    
    /**
     * Create new invoice for current tenant
     */
    public static function create(array $data): int {
        // Auto-generate invoice number for this tenant
        $data['invoice_number'] = 'INV-' . TenantDB::getNextSequence('invoice');
        
        return TenantDB::insert('invoices', $data);
    }
    
    /**
     * Update invoice 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 invoices SET " . implode(', ', $setParts) . " WHERE id = ? AND company_id = ?";
        
        try {
            $stmt = $pdo->prepare($query);
            return $stmt->execute($values);
        } catch (PDOException $e) {
            error_log("TenantInvoice Update Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete invoice 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 invoices WHERE id = ? AND company_id = ?");
            return $stmt->execute([$id, $companyId]);
        } catch (PDOException $e) {
            error_log("TenantInvoice Delete Error: " . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Get invoice items for current tenant
     */
    public static function getItems(int $invoiceId): array {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return [];
        }
        
        try {
            $stmt = $pdo->prepare("
                SELECT ii.* FROM invoice_items ii
                JOIN invoices i ON ii.invoice_id = i.id
                WHERE ii.invoice_id = ? AND i.company_id = ?
                ORDER BY ii.id ASC
            ");
            $stmt->execute([$invoiceId, $companyId]);
            return $stmt->fetchAll() ?: [];
        } catch (PDOException $e) {
            error_log("TenantInvoice Get Items Error: " . $e->getMessage());
            return [];
        }
    }
    
    /**
     * Add invoice item for current tenant
     */
    public static function addItem(int $invoiceId, array $itemData): int {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            throw new Exception("No tenant context set");
        }
        
        // Verify invoice belongs to current tenant
        $stmt = $pdo->prepare("SELECT id FROM invoices WHERE id = ? AND company_id = ?");
        $stmt->execute([$invoiceId, $companyId]);
        
        if (!$stmt->fetch()) {
            throw new Exception("Invoice not found or access denied");
        }
        
        $itemData['invoice_id'] = $invoiceId;
        return TenantDB::insert('invoice_items', $itemData);
    }
    
    /**
     * Search invoices for current tenant
     */
    public static function search(string $term): array {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if (!$companyId) {
            return [];
        }
        
        try {
            $stmt = $pdo->prepare("
                SELECT i.*, c.name as client_name FROM invoices i
                LEFT JOIN clients c ON i.client_id = c.id
                WHERE i.company_id = ? AND (
                    i.invoice_number LIKE ? OR 
                    i.status LIKE ? OR 
                    c.name LIKE ?
                ) 
                ORDER BY i.created_at DESC
            ");
            $stmt->execute([$companyId, "%$term%", "%$term%", "%$term%"]);
            return $stmt->fetchAll() ?: [];
        } catch (PDOException $e) {
            error_log("TenantInvoice Search Error: " . $e->getMessage());
            return [];
        }
    }
}
