<?php

namespace App\Http\Controllers\Admin\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use ZipArchive;

class UploadController extends Controller
{
    public function index()
    {
        // Check existing RAE_Exported_Table.tab file
        $tablePath = public_path('img/RAE_Exported_Table.tab');
        $tableExists = file_exists($tablePath);
        $tableSize = $tableExists ? filesize($tablePath) : 0;
        $tableModified = $tableExists ? filemtime($tablePath) : null;

        // Check existing Icons folder
        $iconsPath = public_path('img/Icons');
        $iconsExists = is_dir($iconsPath);
        $iconsCount = 0;
        
        if ($iconsExists) {
            $files = glob($iconsPath . '/*');
            $iconsCount = count($files);
        }

        // Get PHP limits
        $phpLimits = [
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'post_max_size' => ini_get('post_max_size'),
            'max_execution_time' => ini_get('max_execution_time'),
            'memory_limit' => ini_get('memory_limit'),
        ];

        return Inertia::render('admin/settings/upload/index', [
            'tableInfo' => [
                'exists' => $tableExists,
                'size' => $tableSize,
                'modified' => $tableModified,
            ],
            'iconsInfo' => [
                'exists' => $iconsExists,
                'count' => $iconsCount,
            ],
            'phpLimits' => $phpLimits,
        ]);
    }

    public function uploadTable(Request $request)
    {
        try {
            $request->validate([
                'file' => 'required|file|max:51200', // Max 50MB
            ]);

            $file = $request->file('file');
            
            if (!$file) {
                \Log::error('Upload Table: No file received');
                return back()->with('error', 'File tidak diterima');
            }

            // Check file extension
            $extension = strtolower($file->getClientOriginalExtension());
            \Log::info('Upload Table: Received file with extension: ' . $extension);
            
            if ($extension !== 'tab') {
                return back()->with('error', 'File harus berekstensi .tab');
            }

            // Move file to public/img with proper name
            $destinationPath = public_path('img');
            $fileName = 'RAE_Exported_Table.tab';

            // Delete old file if exists
            $oldFilePath = $destinationPath . '/' . $fileName;
            if (file_exists($oldFilePath)) {
                unlink($oldFilePath);
            }

            // Move new file
            $file->move($destinationPath, $fileName);
            
            \Log::info('Upload Table: File moved successfully to ' . $destinationPath . '/' . $fileName);

            return back()->with('success', 'File RAE_Exported_Table.tab berhasil diupload!');
        } catch (\Exception $e) {
            \Log::error('Upload Table Error: ' . $e->getMessage());
            return back()->with('error', 'Gagal upload: ' . $e->getMessage());
        }
    }

    public function uploadIcons(Request $request)
    {
        try {
            $request->validate([
                'file' => 'required|file|mimes:zip|max:102400', // Max 100MB
            ]);

            $file = $request->file('file');
            
            if (!$file) {
                \Log::error('Upload Icons: No file received');
                return back()->with('error', 'File tidak diterima');
            }
            
            \Log::info('Upload Icons: Received file: ' . $file->getClientOriginalName());
            
            $zip = new ZipArchive;

            // Create temp path for zip
            $tempPath = storage_path('app/temp');
            if (!is_dir($tempPath)) {
                mkdir($tempPath, 0755, true);
            }

            $zipPath = $tempPath . '/' . $file->getClientOriginalName();
            $file->move($tempPath, $file->getClientOriginalName());

            // Extract zip
            if ($zip->open($zipPath) === true) {
                $destinationPath = public_path('img/Icons');
                
                // Create Icons folder if not exists
                if (!is_dir($destinationPath)) {
                    mkdir($destinationPath, 0755, true);
                }

                // Extract files
                $extractedCount = 0;
                for ($i = 0; $i < $zip->numFiles; $i++) {
                    $filename = $zip->getNameIndex($i);
                    
                    // Skip directories and hidden files
                    if (substr($filename, -1) === '/' || strpos($filename, '__MACOSX') !== false) {
                        continue;
                    }

                    // Get just the filename without directory structure
                    $basename = basename($filename);
                    if (empty($basename)) {
                        continue;
                    }

                    // Extract file content and save
                    $content = $zip->getFromIndex($i);
                    if ($content !== false) {
                        file_put_contents($destinationPath . '/' . $basename, $content);
                        $extractedCount++;
                    }
                }

                $zip->close();

                // Clean up temp zip file
                if (file_exists($zipPath)) {
                    unlink($zipPath);
                }

                \Log::info('Upload Icons: Extracted ' . $extractedCount . ' files');
                return back()->with('success', "Berhasil mengekstrak {$extractedCount} file ke folder Icons!");
            } else {
                // Clean up temp zip file on error
                if (file_exists($zipPath)) {
                    unlink($zipPath);
                }
                
                \Log::error('Upload Icons: Failed to open ZIP file');
                return back()->with('error', 'Gagal membuka file ZIP. Pastikan file valid.');
            }
        } catch (\Exception $e) {
            \Log::error('Upload Icons Error: ' . $e->getMessage());
            return back()->with('error', 'Gagal upload: ' . $e->getMessage());
        }
    }
}
