<?php

namespace App\Services;

use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Imports\BaseImport;
use App\Exports\BaseExport;

class ExcelService
{
    protected $importClass;
    protected $exportClass;

    public function import($file, $importClass, $options = [])
    {
        try {
            Log::info('Starting Excel import', ['file' => $file->getClientOriginalName()]);
            
            $import = new $importClass($options);
            
            Excel::import($import, $file);
            
            $results = $import->getResults();
            
            Log::info('Excel import completed', [
                'success_count' => $results['success_count'] ?? 0,
                'error_count' => $results['error_count'] ?? 0,
                'errors' => $results['errors'] ?? []
            ]);
            
            return $results;
        } catch (\Exception $e) {
            Log::error('Excel import failed', [
                'error' => $e->getMessage(),
                'file' => $file->getClientOriginalName()
            ]);
            
            throw $e;
        }
    }

    public function export($exportClass, $filename, $options = [])
    {
        try {
            Log::info('Starting Excel export', ['filename' => $filename]);
            
            $export = new $exportClass($options);
            
            return Excel::download($export, $filename);
        } catch (\Exception $e) {
            Log::error('Excel export failed', [
                'error' => $e->getMessage(),
                'filename' => $filename
            ]);
            
            throw $e;
        }
    }

    public function generateTemplate($templateClass, $filename)
    {
        try {
            Log::info('Generating Excel template', ['filename' => $filename]);
            
            $template = new $templateClass();
            
            return Excel::download($template, $filename);
        } catch (\Exception $e) {
            Log::error('Template generation failed', [
                'error' => $e->getMessage(),
                'filename' => $filename
            ]);
            
            throw $e;
        }
    }

    public function validateFile($file, $maxSize = 10240, $allowedExtensions = ['xlsx', 'xls', 'csv'])
    {
        if (!$file) {
            throw new \Exception('No file provided');
        }

        if ($file->getSize() > $maxSize * 1024) {
            throw new \Exception('File size exceeds maximum allowed size');
        }

        $extension = strtolower($file->getClientOriginalExtension());
        
        if (!in_array($extension, $allowedExtensions)) {
            throw new \Exception('Invalid file type. Allowed types: ' . implode(', ', $allowedExtensions));
        }

        return true;
    }

    public function storeFile($file, $path = 'excel/imports')
    {
        $filename = time() . '_' . $file->getClientOriginalName();
        
        return $file->storeAs($path, $filename, 'local');
    }

    public function getImportHistory($limit = 50)
    {
        // This would typically query an import_history table
        // For now, return empty array
        return [];
    }
}
