<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

trait ExcelUploadTrait
{
    /**
     * Store uploaded Excel file to storage
     * 
     * @param UploadedFile $file
     * @param string $prefix - Prefix for filename (e.g., 'forecast', 'raw_materials')
     * @return string - Stored file path relative to storage/app/public
     */
    protected function storeUploadedExcel(UploadedFile $file, string $prefix = 'upload'): string
    {
        $now = Carbon::now();
        $year = $now->format('Y');
        $month = $now->format('m');
        
        // Create directory structure: uploads/excel/{year}/{month}
        $directory = "uploads/excel/{$year}/{$month}";
        
        // Generate unique filename: {prefix}_{timestamp}_{original_name}
        $timestamp = $now->format('YmdHis');
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        
        // Sanitize original filename (remove extension, keep only alphanumeric and basic chars)
        $sanitizedName = preg_replace('/\.[^.]+$/', '', $originalName); // Remove extension
        $sanitizedName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $sanitizedName); // Replace special chars
        $sanitizedName = substr($sanitizedName, 0, 50); // Limit length
        
        $filename = "{$prefix}_{$timestamp}_{$sanitizedName}.{$extension}";
        
        // Store file to public disk
        $path = $file->storeAs($directory, $filename, 'public');
        
        return $path;
    }
    
    /**
     * Delete uploaded Excel file from storage
     * 
     * @param string|null $filePath - File path relative to storage/app/public
     * @return bool
     */
    protected function deleteUploadedExcel(?string $filePath): bool
    {
        if (empty($filePath)) {
            return false;
        }
        
        $disk = Storage::disk('public');
        
        if ($disk->exists($filePath)) {
            return $disk->delete($filePath);
        }
        
        return false;
    }
    
    /**
     * Get full URL for uploaded Excel file
     * 
     * @param string|null $filePath - File path relative to storage/app/public
     * @return string|null
     */
    protected function getUploadedExcelUrl(?string $filePath): ?string
    {
        if (empty($filePath)) {
            return null;
        }
        
        return Storage::disk('public')->url($filePath);
    }
    
    /**
     * Trim all values in an array recursively
     * Useful for cleaning Excel data that may have trailing/leading spaces
     * 
     * @param array $data
     * @return array
     */
    protected function trimExcelRow(array $data): array
    {
        return array_map(function($value) {
            if (is_string($value)) {
                return trim($value);
            }
            return $value;
        }, $data);
    }
    
    /**
     * Trim all rows in Excel data
     * 
     * @param array $rows
     * @return array
     */
    protected function trimExcelData(array $rows): array
    {
        return array_map(function($row) {
            return $this->trimExcelRow($row);
        }, $rows);
    }
}
