<?php
// src/ReportGenerator.php - Report Generation Utilities

require_once __DIR__ . '/Database.php';

class ReportGenerator {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Format report data for display
     */
    public function formatReportData($report_data) {
        if (!isset($report_data['rows'])) {
            return [];
        }

        $formatted = [];
        $headers = $report_data['headers'] ?? [];
        
        foreach ($report_data['rows'] as $row) {
            $formatted_row = [];
            
            foreach ($row as $index => $cell) {
                $header = $headers[$index] ?? 'column_' . $index;
                $formatted_row[$header] = $cell;
            }
            
            $formatted[] = $formatted_row;
        }
        
        return $formatted;
    }

    /**
     * Calculate totals from report data
     */
    public function calculateTotals($report_data, $metric_fields = []) {
        $totals = [];
        
        foreach ($metric_fields as $field) {
            $totals[$field] = 0;
        }
        
        foreach ($report_data as $row) {
            foreach ($metric_fields as $field) {
                if (isset($row[$field])) {
                    $totals[$field] += floatval($row[$field]);
                }
            }
        }
        
        return $totals;
    }

    /**
     * Export report to CSV format
     */
    public function exportToCSV($report_data, $filename = 'report.csv') {
        if (empty($report_data)) {
            return false;
        }

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        $output = fopen('php://output', 'w');
        
        // Write headers
        $headers = array_keys($report_data[0]);
        fputcsv($output, $headers);
        
        // Write data
        foreach ($report_data as $row) {
            fputcsv($output, $row);
        }
        
        fclose($output);
        exit;
    }

    /**
     * Export report to JSON format
     */
    public function exportToJSON($report_data, $filename = 'report.json') {
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        echo json_encode($report_data, JSON_PRETTY_PRINT);
        exit;
    }

    /**
     * Cache report to database
     */
    public function cacheReport($report_name, $report_data, $cache_hours = 1) {
        try {
            $stmt = $this->db->prepare("
                INSERT INTO cached_reports (report_name, report_data, generated_at, cache_expiry)
                VALUES (:name, :data, NOW(), DATE_ADD(NOW(), INTERVAL :hours HOUR))
            ");
            
            $stmt->execute([
                ':name' => $report_name,
                ':data' => json_encode($report_data),
                ':hours' => $cache_hours
            ]);
            
            return true;
        } catch (PDOException $e) {
            error_log('Report Cache Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get cached report from database
     */
    public function getCachedReport($report_name) {
        try {
            $stmt = $this->db->prepare("
                SELECT report_data, generated_at 
                FROM cached_reports 
                WHERE report_name = :name 
                AND cache_expiry > NOW()
                ORDER BY generated_at DESC 
                LIMIT 1
            ");
            
            $stmt->execute([':name' => $report_name]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result) {
                return json_decode($result['report_data'], true);
            }
            
            return null;
        } catch (PDOException $e) {
            error_log('Report Fetch Error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Clear expired cache entries
     */
    public function clearExpiredCache() {
        try {
            $stmt = $this->db->prepare("DELETE FROM cached_reports WHERE cache_expiry < NOW()");
            $stmt->execute();
            return $stmt->rowCount();
        } catch (PDOException $e) {
            error_log('Cache Clear Error: ' . $e->getMessage());
            return 0;
        }
    }

    /**
     * Clear all cache entries
     */
    public function clearAllCache() {
        try {
            $stmt = $this->db->prepare("TRUNCATE TABLE cached_reports");
            $stmt->execute();
            return true;
        } catch (PDOException $e) {
            error_log('Cache Clear All Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Get cache statistics
     */
    public function getCacheStats() {
        try {
            $stmt = $this->db->query("
                SELECT 
                    COUNT(*) as total_reports,
                    SUM(LENGTH(report_data)) as total_size,
                    MIN(generated_at) as oldest_report,
                    MAX(generated_at) as newest_report
                FROM cached_reports
                WHERE cache_expiry > NOW()
            ");
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log('Cache Stats Error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Format currency values
     */
    public function formatCurrency($amount, $currency = 'USD') {
        $symbols = [
            'USD' => '$',
            'EUR' => '€',
            'GBP' => '£',
            'PKR' => 'Rs.',
            'INR' => '₹'
        ];
        
        $symbol = $symbols[$currency] ?? $currency . ' ';
        return $symbol . number_format($amount, 2);
    }

    /**
     * Format percentage values
     */
    public function formatPercentage($value, $decimals = 2) {
        return number_format($value, $decimals) . '%';
    }

    /**
     * Format large numbers
     */
    public function formatNumber($number) {
        if ($number >= 1000000) {
            return number_format($number / 1000000, 2) . 'M';
        } elseif ($number >= 1000) {
            return number_format($number / 1000, 2) . 'K';
        }
        return number_format($number);
    }

    /**
     * Calculate percentage change
     */
    public function calculateChange($current, $previous) {
        if ($previous == 0) {
            return $current > 0 ? 100 : 0;
        }
        
        return (($current - $previous) / $previous) * 100;
    }

    /**
     * Group report data by dimension
     */
    public function groupByDimension($report_data, $dimension) {
        $grouped = [];
        
        foreach ($report_data as $row) {
            $key = $row[$dimension] ?? 'Unknown';
            
            if (!isset($grouped[$key])) {
                $grouped[$key] = [
                    'dimension' => $key,
                    'impressions' => 0,
                    'clicks' => 0,
                    'earnings' => 0
                ];
            }
            
            $grouped[$key]['impressions'] += floatval($row['impressions'] ?? 0);
            $grouped[$key]['clicks'] += floatval($row['clicks'] ?? 0);
            $grouped[$key]['earnings'] += floatval($row['earnings'] ?? 0);
        }
        
        return array_values($grouped);
    }
}

?>