<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\File;
use App\Models\Translation\FileTranslation;
use App\Models\Webinar;
use App\Models\WebinarChapterItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Validator;

class FileController extends Controller
{
    public function store(Request $request)
    {
        $this->authorize('admin_webinars_edit');

        // Handle both ajax['new'] format and direct form data format
        $ajaxData = $request->get('ajax');
        if (!empty($ajaxData) && isset($ajaxData['new'])) {
            $data = $ajaxData['new'];
            
            // Ensure allowed_users is an array if it exists
            if (isset($data['allowed_users']) && !is_array($data['allowed_users'])) {
                $data['allowed_users'] = [$data['allowed_users']];
            }
        } else {
            // Handle FormData format - parse nested array keys like ajax[new][field]
            $allRequestData = $request->all();
            
            \Log::info('File store - Request data structure', [
                'has_ajax_key' => isset($allRequestData['ajax']),
                'ajax_type' => isset($allRequestData['ajax']) ? gettype($allRequestData['ajax']) : 'N/A',
                'ajax_keys' => isset($allRequestData['ajax']) && is_array($allRequestData['ajax']) ? array_keys($allRequestData['ajax']) : 'N/A',
                'all_keys' => array_keys($allRequestData),
            ]);
            
            // Check if data is in ajax[new][field] format (from FormData)
            // Laravel should automatically parse ajax[new][field] into nested arrays
            if (isset($allRequestData['ajax']) && is_array($allRequestData['ajax']) && isset($allRequestData['ajax']['new'])) {
                $data = $allRequestData['ajax']['new'];
                \Log::info('File store - Using ajax[new] format', ['data_keys' => array_keys($data)]);
            } else {
                // Direct form data format (for FormData/file uploads)
                // Extract only the fields we need
                $data = [
                    'webinar_id' => $request->get('webinar_id'),
                    'chapter_id' => $request->get('chapter_id'),
                    'title' => $request->get('title'),
                    'description' => $request->get('description'),
                    'storage' => $request->get('storage'),
                    'file_path' => $request->get('file_path'),
                    'file_type' => $request->get('file_type'),
                    'volume' => $request->get('volume'),
                    'accessibility' => $request->get('accessibility'),
                    'interactive_type' => $request->get('interactive_type'),
                    'interactive_file_name' => $request->get('interactive_file_name'),
                    'interactive_file_path' => $request->get('interactive_file_path'),
                    'downloadable' => $request->get('downloadable'),
                    'online_viewer' => $request->get('online_viewer'),
                    'sequence_content' => $request->get('sequence_content'),
                    'check_previous_parts' => $request->get('check_previous_parts'),
                    'access_after_day' => $request->get('access_after_day'),
                    'status' => $request->get('status'),
                    'locale' => $request->get('locale'),
                ];
                
                // Handle allowed_users - can come as array or multiple entries
                $allowedUsers = $request->get('allowed_users');
                if (is_array($allowedUsers)) {
                    $data['allowed_users'] = array_filter($allowedUsers);
                } elseif (!empty($allowedUsers)) {
                    $data['allowed_users'] = [$allowedUsers];
                } else {
                    $data['allowed_users'] = [];
                }
            }
            
            // Handle s3_file separately
            if ($request->hasFile('s3_file')) {
                $data['s3_file'] = $request->file('s3_file');
            }
            
            // Remove null values to match expected format (but keep empty arrays for allowed_users)
            $data = array_filter($data, function($value, $key) {
                return $value !== null || $key === 'allowed_users';
            }, ARRAY_FILTER_USE_BOTH);
        }

        if (empty($data['storage'])) {
            $data['storage'] = 'upload';
        }

        if (!empty($data['file_path']) and is_array($data['file_path'])) {
            $data['file_path'] = $data['file_path'][0];
        }

        $sourceRequiredFileType = ['external_link', 's3', 'google_drive', 'upload'];
        $sourceDefaultFileTypeAndVolume = ['youtube', 'vimeo', 'iframe'];

        if (in_array($data['storage'], $sourceDefaultFileTypeAndVolume)) {
            $data['file_type'] = 'video';
            $data['volume'] = 0;
        }

        $rules = [
            'webinar_id' => 'required',
            'chapter_id' => 'required',
            'title' => 'required|max:255',
            'accessibility' => 'required|' . Rule::in(File::$accessibility),
            'file_path' => 'required',
            'file_type' => Rule::requiredIf(in_array($data['storage'], $sourceRequiredFileType)),
            'volume' => Rule::requiredIf(in_array($data['storage'], $sourceRequiredFileType)),
            'description' => 'nullable',
        ];

        if ($data['storage'] == 'upload_archive') {
            $rules['interactive_type'] = 'required';
            $rules['interactive_file_name'] = Rule::requiredIf($data['interactive_type'] == 'custom');
        }

        if ($data['storage'] == 's3') {
            $rules ['file_path'] = 'nullable';
            $rules ['s3_file'] = 'required';
        }

        // Log the data being validated
        \Log::info('File store - Data being validated', [
            'data_keys' => array_keys($data),
            'data' => $data,
            'storage' => $data['storage'] ?? 'NOT SET',
        ]);

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            \Log::error('File store - Validation failed', [
                'errors' => $validator->errors()->toArray(),
                'data' => $data,
            ]);
            
            return response()->json([
                'code' => 422,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        $data['downloadable'] = !empty($data['downloadable']);
        if (in_array($data['storage'], ['youtube', 'vimeo', 'iframe', 'google_drive', 'upload_archive'])) {
            $data['downloadable'] = false;
        } elseif (in_array($data['storage'], ['external_link', 's3']) and $data['file_type'] != 'video') {
            $data['downloadable'] = true;
        }

        if (!empty($data['sequence_content']) and $data['sequence_content'] == 'on') {
            $data['check_previous_parts'] = (!empty($data['check_previous_parts']) and $data['check_previous_parts'] == 'on');
            $data['access_after_day'] = !empty($data['access_after_day']) ? $data['access_after_day'] : null;
        } else {
            $data['check_previous_parts'] = false;
            $data['access_after_day'] = null;
        }

        $webinar = Webinar::find($data['webinar_id']);

        if (!empty($webinar)) {
            $user = $webinar->creator;
            
            if (empty($user)) {
                return response()->json([
                    'code' => 422,
                    'message' => 'Webinar creator not found',
                ], 422);
            }
            
            // Verify chapter exists if chapter_id is provided
            if (!empty($data['chapter_id'])) {
                $chapterExists = DB::table('webinar_chapters')->where('id', $data['chapter_id'])->exists();
                if (!$chapterExists) {
                    return response()->json([
                        'code' => 422,
                        'message' => 'Chapter not found',
                        'errors' => [
                            'chapter_id' => ['The selected chapter does not exist']
                        ],
                    ], 422);
                }
            }

            $volumeMatches = [''];
            $fileInfos = null;

            if ($data['storage'] == 'upload_archive') {
                $fileInfos = $this->fileInfo($data['file_path']);

                if (empty($fileInfos) or $fileInfos['extension'] != 'zip') {
                    return response()->json([
                        'code' => 422,
                        'message' => 'Invalid file type',
                        'errors' => [
                            'file_path' => [trans('validation.mimes', ['attribute' => 'file', 'values' => 'zip'])]
                        ],
                    ], 422);
                }

                $fileInfos['extension'] = 'archive';
                $data['interactive_file_path'] = $this->handleUnZipFile($data, $user->id);

            } elseif ($data['storage'] == 'upload') {
                $uploadFile = $this->fileInfo($data['file_path']);
                $data['volume'] = $uploadFile['size'];
            } elseif ($data['storage'] == 's3') {
                $result = $this->uploadFileToS3($data['s3_file'], $user->id);

                if (!$result['status']) {
                    return $result['path'];
                }

                $data['file_path'] = $result['path'];
                $fileInfos = [];
                $fileInfos['extension'] = $data['file_type'];

                preg_match('!\d+!', $data['volume'], $volumeMatches);
                $fileInfos['size'] = isset($volumeMatches[0]) ? $volumeMatches[0] * 1048576 : 0;
            } else {
                preg_match('!\d+!', $data['volume'], $volumeMatches);
            }

            try {
                DB::beginTransaction();
                
                $file = new File();
                $file->creator_id = (int) $user->id;
                $file->webinar_id = (int) $data['webinar_id'];
                $file->chapter_id = !empty($data['chapter_id']) ? (int) $data['chapter_id'] : null;
                $file->file = $data['file_path'];
                $file->volume = formatSizeUnits(!empty($fileInfos) ? $fileInfos['size'] : $data['volume']);
                $file->file_type = !empty($fileInfos) ? $fileInfos['extension'] : $data['file_type'];
                $file->accessibility = $data['accessibility'];
                $file->storage = $data['storage'];
                $file->interactive_type = $data['interactive_type'] ?? null;
                $file->interactive_file_name = $data['interactive_file_name'] ?? null;
                $file->interactive_file_path = $data['interactive_file_path'] ?? null;
                // Fix boolean fields for database (convert to 0/1 for MySQL)
                $file->downloadable = (bool) $data['downloadable'] ? 1 : 0;
                $file->online_viewer = (!empty($data['online_viewer']) and ($data['online_viewer'] == 'on' || $data['online_viewer'] == '1' || $data['online_viewer'] === true)) ? 1 : 0;
                $file->check_previous_parts = (bool) $data['check_previous_parts'] ? 1 : 0;
                $file->access_after_day = !empty($data['access_after_day']) ? (int) $data['access_after_day'] : null;
                $file->status = (!empty($data['status']) and ($data['status'] == 'on' || $data['status'] == '1')) ? File::$Active : File::$Inactive;
                $file->created_at = time();
                
                try {
                    // Verify all foreign keys exist before inserting
                    $creatorExists = DB::table('users')->where('id', $file->creator_id)->exists();
                    $webinarExists = DB::table('webinars')->where('id', $file->webinar_id)->exists();
                    $chapterExists = empty($file->chapter_id) ? true : DB::table('webinar_chapters')->where('id', $file->chapter_id)->exists();
                    
                    if (!$creatorExists || !$webinarExists || !$chapterExists) {
                        DB::rollBack();
                        \Log::error('Foreign key validation failed', [
                            'creator_exists' => $creatorExists,
                            'webinar_exists' => $webinarExists,
                            'chapter_exists' => $chapterExists,
                            'creator_id' => $file->creator_id,
                            'webinar_id' => $file->webinar_id,
                            'chapter_id' => $file->chapter_id,
                        ]);
                        
                        return response()->json([
                            'code' => 422,
                            'message' => 'Foreign key constraint violation',
                            'errors' => array_filter([
                                'creator_id' => !$creatorExists ? ['Creator does not exist'] : null,
                                'webinar_id' => !$webinarExists ? ['Webinar does not exist'] : null,
                                'chapter_id' => !$chapterExists ? ['Chapter does not exist'] : null,
                            ]),
                        ], 422);
                    }
                    
                    // Use Eloquent save() method - more reliable than insertGetId
                    try {
                        // Enable query logging to see what SQL is executed
                        DB::enableQueryLog();
                        $saved = $file->save();
                        $queries = DB::getQueryLog();
                        DB::disableQueryLog();
                        
                        if (!$saved) {
                            DB::rollBack();
                            \Log::error('File save failed - save() returned false', [
                                'saved' => $saved,
                                'file_attributes' => $file->getAttributes(),
                            ]);
                            
                            return response()->json([
                                'code' => 500,
                                'message' => 'Failed to save file record.',
                            ], 500);
                        }
                        
                        // Get the ID using multiple methods to ensure we have it
                        $fileId = $file->getKey(); // Use getKey() instead of ->id
                        
                        // If still 0, try getting from PDO lastInsertId immediately after save
                        if (empty($fileId) || $fileId == 0) {
                            $pdo = DB::getPdo();
                            $lastInsertId = $pdo->lastInsertId();
                            if (!empty($lastInsertId) && $lastInsertId > 0 && $lastInsertId != '0') {
                                $fileId = (int) $lastInsertId;
                                $file->id = $fileId; // Set it on the model
                            } else {
                                // Try to find the record by querying unique fields
                                $foundFile = DB::table('files')
                                    ->where('creator_id', $file->creator_id)
                                    ->where('webinar_id', $file->webinar_id)
                                    ->where('chapter_id', $file->chapter_id)
                                    ->where('file', $file->file)
                                    ->where('created_at', $file->created_at)
                                    ->orderBy('id', 'desc')
                                    ->first();
                                
                                if ($foundFile && !empty($foundFile->id)) {
                                    $fileId = $foundFile->id;
                                    $file->id = $fileId;
                                }
                            }
                        }
                    } catch (\Exception $saveEx) {
                        DB::rollBack();
                        \Log::error('File save exception: ' . $saveEx->getMessage(), [
                            'exception' => get_class($saveEx),
                            'trace' => $saveEx->getTraceAsString(),
                            'file_attributes' => $file->getAttributes(),
                        ]);
                        
                        return response()->json([
                            'code' => 500,
                            'message' => 'Error saving file: ' . $saveEx->getMessage(),
                        ], 500);
                    }
                    
                    \Log::info('File insert result', [
                        'file_id' => $fileId,
                        'file_getKey' => $file->getKey(),
                        'file_id_property' => $file->id ?? 'null',
                        'pdo_lastInsertId' => DB::getPdo()->lastInsertId(),
                        'saved' => $saved,
                        'queries' => $queries ?? [],
                        'creator_id' => $file->creator_id,
                        'webinar_id' => $file->webinar_id,
                        'chapter_id' => $file->chapter_id ?? 'null',
                        'storage' => $file->storage,
                        'file_type' => $file->file_type,
                    ]);
                    
                    if (empty($fileId) || $fileId == 0) {
                        DB::rollBack();
                        \Log::error('File save returned no ID after all attempts', [
                            'file_id' => $fileId,
                            'file_getKey' => $file->getKey(),
                            'file_id_property' => $file->id ?? 'null',
                            'file_attributes' => $file->getAttributes(),
                            'pdo_lastInsertId' => DB::getPdo()->lastInsertId(),
                            'saved' => $saved ?? false,
                            'queries' => $queries ?? [],
                        ]);
                        
                        return response()->json([
                            'code' => 500,
                            'message' => 'Failed to insert file record. Database returned no ID. This may indicate a database configuration issue or constraint violation.',
                        ], 500);
                    }
                } catch (\Illuminate\Database\QueryException $saveException) {
                    DB::rollBack();
                    \Log::error('File save database exception: ' . $saveException->getMessage(), [
                        'sql' => $saveException->getSql(),
                        'bindings' => $saveException->getBindings(),
                        'trace' => $saveException->getTraceAsString(),
                        'data' => $data,
                        'file_attributes' => $file->getAttributes(),
                    ]);
                    
                    return response()->json([
                        'code' => 500,
                        'message' => 'Database error saving file: ' . $saveException->getMessage(),
                    ], 500);
                } catch (\Exception $saveException) {
                    DB::rollBack();
                    \Log::error('File save exception: ' . $saveException->getMessage(), [
                        'trace' => $saveException->getTraceAsString(),
                        'data' => $data,
                        'file_attributes' => $file->getAttributes(),
                    ]);
                    
                    return response()->json([
                        'code' => 500,
                        'message' => 'Error saving file: ' . $saveException->getMessage(),
                    ], 500);
                }
                
                // $fileId is already set from insertGetId above
                if (!empty($fileId) && $fileId > 0) {
                    try {
                        $locale = !empty($data['locale']) ? mb_strtolower($data['locale']) : mb_strtolower(app()->getLocale());
                        
                        // Create or update file translation
                        FileTranslation::updateOrCreate([
                            'file_id' => $fileId,
                            'locale' => $locale,
                        ], [
                            'title' => $data['title'],
                            'description' => $data['description'] ?? null,
                        ]);

                        // Handle allowed users for lecture access control
                        if (!empty($data['allowed_users']) && is_array($data['allowed_users'])) {
                            // Filter out empty values and convert to integers
                            $allowedUsers = array_filter(array_map('intval', $data['allowed_users']));
                            if (!empty($allowedUsers)) {
                                // Sync with pivot data - lecture_user table requires lecture_type and created_at
                                $syncData = [];
                                $timestamp = time();
                                foreach ($allowedUsers as $userId) {
                                    $syncData[$userId] = [
                                        'lecture_type' => 'file',
                                        'created_at' => $timestamp,
                                    ];
                                }
                                $file->allowedUsers()->sync($syncData);
                            } else {
                                $file->allowedUsers()->detach();
                            }
                        } else {
                            // If no users specified, clear all restrictions
                            $file->allowedUsers()->detach();
                        }

                        if (!empty($file->chapter_id)) {
                            WebinarChapterItem::makeItem($file->creator_id, $file->chapter_id, $fileId, WebinarChapterItem::$chapterFile);
                        }

                        DB::commit();
                        
                        \Log::info('File created successfully', [
                            'file_id' => $fileId,
                            'webinar_id' => $data['webinar_id'],
                            'chapter_id' => $data['chapter_id'] ?? null,
                        ]);
                        
                        return response()->json([
                            'code' => 200,
                            'message' => 'File created successfully',
                        ], 200);
                    } catch (\Exception $e) {
                        DB::rollBack();
                        \Log::error('Error creating file translation or relations: ' . $e->getMessage(), [
                            'file_id' => $fileId,
                            'trace' => $e->getTraceAsString(),
                            'data' => $data,
                        ]);
                        
                        return response()->json([
                            'code' => 500,
                            'message' => 'File created but failed to create translation: ' . $e->getMessage(),
                        ], 500);
                    }
                } else {
                    DB::rollBack();
                    return response()->json([
                        'code' => 500,
                        'message' => 'Failed to create file record',
                    ], 500);
                }
            } catch (\Illuminate\Database\QueryException $e) {
                DB::rollBack();
                \Log::error('File creation database error: ' . $e->getMessage(), [
                    'sql' => $e->getSql(),
                    'bindings' => $e->getBindings(),
                    'trace' => $e->getTraceAsString(),
                    'data' => $data,
                ]);
                
                return response()->json([
                    'code' => 500,
                    'message' => 'Database error creating file: ' . $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ], 500);
            } catch (\Exception $e) {
                DB::rollBack();
                \Log::error('File creation error: ' . $e->getMessage(), [
                    'trace' => $e->getTraceAsString(),
                    'data' => $data,
                ]);
                
                return response()->json([
                    'code' => 500,
                    'message' => 'Error creating file: ' . $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ], 500);
            }
        }

        return response()->json([], 422);
    }


    public function edit(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $file = File::where('id', $id)
            ->with('allowedUsers')
            ->first();

        if (!empty($file)) {
            $locale = $request->get('locale', app()->getLocale());
            if (empty($locale)) {
                $locale = app()->getLocale();
            }
            storeContentLocale($locale, $file->getTable(), $file->id);

            $file->title = $file->getTitleAttribute();
            $file->description = $file->getDescriptionAttribute();
            $file->file_path = $file->file;
            $file->locale = mb_strtoupper($locale);
            
            // Get allowed users IDs
            $file->allowed_users = $file->allowedUsers->pluck('id')->toArray();
            
            \Log::info('File edit - Loading file with allowed users', [
                'file_id' => $file->id,
                'allowed_users_count' => $file->allowedUsers->count(),
                'allowed_users_ids' => $file->allowed_users,
            ]);

            return response()->json([
                'file' => $file
            ], 200);
        }

        return response()->json([], 422);
    }

    public function update(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $ajaxData = $request->get('ajax');
        if (empty($ajaxData) || !isset($ajaxData[$id])) {
            return response()->json([
                'code' => 422,
                'message' => 'Invalid request data',
            ], 422);
        }

        $data = $ajaxData[$id];

        $sourceRequiredFileType = ['external_link', 's3', 'google_drive', 'upload'];

        if (empty($data['storage'])) {
            $data['storage'] = 'upload';
        }

        if (!empty($data['file_path']) and is_array($data['file_path'])) {
            $data['file_path'] = $data['file_path'][0];
        }

        $rules = [
            'webinar_id' => 'required',
            'chapter_id' => 'required',
            'title' => 'required|max:255',
            'accessibility' => 'required|' . Rule::in(File::$accessibility),
            'file_path' => 'required',
            'file_type' => Rule::requiredIf(in_array($data['storage'], $sourceRequiredFileType)),
            'volume' => Rule::requiredIf(in_array($data['storage'], $sourceRequiredFileType)),
            'description' => 'nullable',
        ];

        if ($data['storage'] == 'upload_archive') {
            $rules['interactive_type'] = 'required';
            $rules['interactive_file_name'] = Rule::requiredIf($data['interactive_type'] == 'custom');
        }

        if ($data['storage'] == 's3') {
            $rules ['file_path'] = 'nullable';
            $rules ['s3_file'] = 'nullable';
        }

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            return response([
                'code' => 422,
                'errors' => $validator->errors(),
            ], 422);
        }

        $data['downloadable'] = !empty($data['downloadable']);
        if (in_array($data['storage'], ['youtube', 'vimeo', 'iframe', 'google_drive', 'upload_archive'])) {
            $data['downloadable'] = false;
        } elseif (in_array($data['storage'], ['external_link', 's3']) and $data['file_type'] != 'video') {
            $data['downloadable'] = true;
        }

        if (!empty($data['sequence_content']) and $data['sequence_content'] == 'on') {
            $data['check_previous_parts'] = (!empty($data['check_previous_parts']) and $data['check_previous_parts'] == 'on');
            $data['access_after_day'] = !empty($data['access_after_day']) ? $data['access_after_day'] : null;
        } else {
            $data['check_previous_parts'] = false;
            $data['access_after_day'] = null;
        }

        $volumeMatches = ['0'];
        $fileInfos = null;

        $file = File::where('id', $id)->first();

        if ($data['storage'] == 'upload_archive') {
            $fileInfos = $this->fileInfo($data['file_path']);

            if (empty($fileInfos) or $fileInfos['extension'] != 'zip') {
                return response([
                    'code' => 422,
                    'errors' => [
                        'file_path' => [trans('validation.mimes', ['attribute' => 'file', 'values' => 'zip'])]
                    ],
                ], 422);
            }

            $fileInfos['extension'] = 'archive';
            $data['interactive_file_path'] = $this->handleUnZipFile($data, $file->creator_id);

        } elseif ($data['storage'] == 'upload') {
            $uploadFile = $this->fileInfo($data['file_path']);
            $data['volume'] = $uploadFile['size'];
        } elseif ($data['storage'] == 's3') {
            if (!empty($data['s3_file'])) {
                $result = $this->uploadFileToS3($data['s3_file'], $file->creator_id);

                if (!$result['status']) {
                    return $result['path'];
                }

                $data['file_path'] = $result['path'];
            }

            $fileInfos = [];
            $fileInfos['extension'] = $data['file_type'];

            preg_match('!\d+!', $data['volume'], $volumeMatches);
            $fileInfos['size'] = isset($volumeMatches[0]) ? $volumeMatches[0] * 1048576 : 0;
        } else {
            preg_match('!\d+!', $data['volume'], $volumeMatches);
        }

        if (!empty($file)) {
            $file->update([
                'file' => $data['file_path'],
                'volume' => formatSizeUnits(!empty($fileInfos) ? $fileInfos['size'] : $data['volume']),
                'file_type' => !empty($fileInfos) ? $fileInfos['extension'] : $data['file_type'],
                'accessibility' => $data['accessibility'],
                'storage' => $data['storage'],
                'interactive_type' => $data['interactive_type'] ?? null,
                'interactive_file_name' => $data['interactive_file_name'] ?? null,
                'interactive_file_path' => $data['interactive_file_path'] ?? null,
                'downloadable' => $data['downloadable'],
                'online_viewer' => (!empty($data['online_viewer']) and $data['online_viewer'] == 'on'),
                'check_previous_parts' => $data['check_previous_parts'],
                'access_after_day' => $data['access_after_day'],
                'status' => (!empty($data['status']) and $data['status'] == 'on') ? File::$Active : File::$Inactive,
                'updated_at' => time()
            ]);

            $locale = !empty($data['locale']) ? mb_strtolower($data['locale']) : mb_strtolower(app()->getLocale());
            
            FileTranslation::updateOrCreate([
                'file_id' => $file->id,
                'locale' => $locale,
            ], [
                'title' => $data['title'],
                'description' => $data['description'],
            ]);

            // Handle allowed users for lecture access control
            \Log::info('=== FILE UPDATE - Processing allowed_users ===', [
                'file_id' => $file->id,
                'has_allowed_users_key' => isset($data['allowed_users']),
                'allowed_users_value' => $data['allowed_users'] ?? 'NOT SET',
                'is_array' => isset($data['allowed_users']) ? is_array($data['allowed_users']) : false,
                'is_empty' => isset($data['allowed_users']) ? empty($data['allowed_users']) : true,
                'full_data' => $data,
            ]);
            
            if (!empty($data['allowed_users']) && is_array($data['allowed_users'])) {
                // Filter out empty values and convert to integers
                $allowedUsers = array_filter(array_map('intval', $data['allowed_users']));
                
                \Log::info('File allowed_users after filtering', [
                    'filtered_array' => $allowedUsers,
                    'count' => count($allowedUsers),
                ]);
                
                if (!empty($allowedUsers)) {
                    // Sync with pivot data - lecture_user table requires lecture_type and created_at
                    $syncData = [];
                    $timestamp = time();
                    foreach ($allowedUsers as $userId) {
                        $syncData[$userId] = [
                            'lecture_type' => 'file',
                            'created_at' => $timestamp,
                        ];
                    }
                    
                    \Log::info('File syncing allowed users', [
                        'sync_data' => $syncData,
                        'user_ids' => array_keys($syncData),
                    ]);
                    
                    $result = $file->allowedUsers()->sync($syncData);
                    
                    \Log::info('File sync result', [
                        'attached' => $result['attached'] ?? [],
                        'detached' => $result['detached'] ?? [],
                        'updated' => $result['updated'] ?? [],
                    ]);
                    
                    // Verify what was saved
                    $file->refresh();
                    $file->load('allowedUsers');
                    \Log::info('File after sync - saved users', [
                        'count' => $file->allowedUsers->count(),
                        'user_ids' => $file->allowedUsers->pluck('id')->toArray(),
                    ]);
                } else {
                    \Log::info('File allowed_users array is empty after filtering, detaching all');
                    $file->allowedUsers()->detach();
                }
            } else {
                \Log::info('File allowed_users is empty or not array, detaching all');
                // If no users specified, clear all restrictions
                $file->allowedUsers()->detach();
            }

            WebinarChapterItem::where('user_id', $file->creator_id)
                ->where('item_id', $file->id)
                ->where('type', WebinarChapterItem::$chapterFile)
                ->delete();

            if (!empty($file->chapter_id)) {
                WebinarChapterItem::makeItem($file->creator_id, $file->chapter_id, $file->id, WebinarChapterItem::$chapterFile);
            }

            removeContentLocale();

            return response()->json([
                'code' => 200,
            ], 200);
        }

        removeContentLocale();

        return response()->json([], 422);
    }

    private function handleUnZipFile($data, $user_id)
    {
        $path = $data['file_path'];
        $interactiveType = $data['interactive_type'] ?? null;
        $interactiveFileName = $data['interactive_file_name'] ?? null;

        $storage = Storage::disk('public');

        $fileInfo = $this->fileInfo($path);

        $extractPath = $user_id . '/' . $fileInfo['name'];
        $storageExtractPath = $storage->url($extractPath);

        if (!$storage->exists($extractPath)) {
            $storage->makeDirectory($extractPath);

            $filePath = public_path($path);

            $zip = new \ZipArchive();
            $res = $zip->open($filePath);

            if ($res) {
                $zip->extractTo(public_path($storageExtractPath));

                $zip->close();
            }
        }

        $fileName = 'index.html';

        if ($interactiveType == 'i_spring') {
            $fileName = 'story.html';
        } elseif ($interactiveType == 'custom') {
            $fileName = $interactiveFileName;
        }

        return $storageExtractPath . '/' . $fileName;
    }

    private function uploadFileToS3($file, $user_id)
    {
        $path = 'store/' . $user_id;

        $result = [
            'path' => null,
            'status' => true
        ];

        try {
            $fileName = time() . $file->getClientOriginalName();

            $storage = Storage::disk('minio');

            if (!$storage->exists($path)) {
                $storage->makeDirectory($path);
            }

            $path = $storage->put($path, $file, $fileName);
            $result['path'] = $storage->url($path);
        } catch (\Exception $ex) {

            $result = [
                'path' => response([
                    'code' => 500,
                    'message' => $ex->getMessage(),
                    'traces' => $ex->getTrace(),
                ], 500),
                'status' => false
            ];
        }

        return $result;
    }

    public function fileInfo($path)
    {
        $file = array();

        $file_path = public_path($path);

        $filePath = pathinfo($file_path);

        $file['name'] = $filePath['filename'];
        $file['extension'] = $filePath['extension'];
        $file['size'] = filesize($file_path);

        return $file;
    }

    public function destroy(Request $request, $id)
    {
        $this->authorize('admin_webinars_edit');

        $file = File::where('id', $id)
            ->first();

        if (!empty($file)) {
            WebinarChapterItem::where('user_id', $file->creator_id)
                ->where('item_id', $file->id)
                ->where('type', WebinarChapterItem::$chapterFile)
                ->delete();

            $file->delete();
        }

        return response()->json([
            'code' => 200
        ], 200);
    }
}
