<?php

namespace App\Http\Controllers;

use App\Enums\FileKey;
use App\Models\Core\File;
use App\Models\Platform;
use App\Models\UserFilePlatform;
use App\Traits\Fileable;
use App\Traits\ModelAction;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;

class GalleryController extends Controller
{
    protected $user;

    use Fileable, ModelAction;

    public function __construct()
    {

        $this->user = auth_user('web');

    }

    public function index()
    {

        $media = $this->user->files()
            ->with('platforms.platform')
            ->where('type', FileKey::GALLERY_FILE->value)
            ->search(['name'])
            ->when(request('slug'), function ($query, $slug) {
                $query->whereHas('platforms', function ($q) use ($slug) {
                    $q->whereHas('platform', function ($qq) use ($slug) {
                        $qq->where('slug', $slug);
                    });
                });
            })
            ->paginate(paginateNumber())
            ->through(fn($file) => [
                'id' => $file->id,
                'title' => $file->name,
                'type' => optional($file->platforms->first())->type,
                'size' => $file->size,
                'date' => $file->created_at->format('d F Y, h:i A'),
                'thumbnail' => imageURL($file, 'gallery'),
                'isVideo' => (getFileTypeFromExtension($file->extension) == 'video'),
                'platform' => optional($file->platforms->first()->platform)->slug,
                'alt' => $file->name
            ]);

        // dd($media);

        return Inertia::render('Gallery/Index', [
            'platforms' => Platform::select('id', 'name', 'slug')->get(),
            'media' => $media,
        ]);
    }

    public function store(Request $request)
    {
        $allowedTypes = site_settings('allowed_file_types', 'jpg,jpeg,png,gif,mp4,mov,avi,webm');

        $request->validate([
            'platform_id' => ['required', function ($attribute, $value, $fail) {
                if ($value !== 'all' && !Platform::where('id', $value)->exists()) {
                    $fail('The selected platform is invalid.');
                }
            }],
            'media' => ['required', 'array', 'min:1'],
            'media.*' => ['required', 'file', 'mimes:' . $allowedTypes, 'max:20480'],
        ], [
            'media.required' => 'Please select at least one file to upload.',
            'media.min' => 'Please select at least one file to upload.',
            'media.*.required' => 'Each file is required.',
            'media.*.file' => 'Each upload must be a valid file.',
            'media.*.mimes' => 'Only ' . strtoupper(str_replace(',', ', ', $allowedTypes)) . ' files are allowed.',
            'media.*.max' => 'Each file must be smaller than 20MB.',
            'platform_id.required' => 'Please select a platform.',
            'platform_id.exists' => 'The selected platform is invalid.',
        ]);



        $fileRows = [];
        foreach ($request->file('media') as $uploadedFile) {
            $response = $this->storeFile(
                file: $uploadedFile,
                location: config("settings.file_path.gallery.path"),
            );

            $fileRows[] = [
                'name' => $response['name'],
                'disk' => $response['disk'],
                'type' => FileKey::GALLERY_FILE->value,
                'size' => $response['size'],
                'extension' => $response['extension'],
                'fileable_id' => $this->user->id,
                'fileable_type' => get_class($this->user),
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }

        $files = $this->user->files()->createMany($fileRows);

        // Handle "all" platforms case
        if ($request->platform_id === 'all') {
            $allPlatforms = Platform::all();
            $pivotRows = [];

            foreach ($files as $file) {
                foreach ($allPlatforms as $platform) {
                    $pivotRows[] = [
                        'user_id' => $this->user->id,
                        'file_id' => $file->id,
                        'platform_id' => $platform->id,
                        'type' => getFileTypeFromExtension($file->extension),
                        'created_at' => now(),
                        'updated_at' => now(),
                    ];
                }
            }
        } else {
            // Handle specific platform case
            $pivotRows = $files->map(fn($file) => [
                'user_id' => $this->user->id,
                'file_id' => $file->id,
                'platform_id' => $request->platform_id,
                'type' => getFileTypeFromExtension($file->extension),
                'created_at' => now(),
                'updated_at' => now(),
            ])->toArray();
        }

        UserFilePlatform::insert($pivotRows);

        $platformMessage = $request->platform_id === 'all' ? ' and made accessible to all platforms' : '';

        return back()->with('success', count($files) . ' file(s) uploaded successfully' . $platformMessage . '.');
    }

    /**
     * Summary of delete
     * @param \Illuminate\Http\Request $request
     * @return RedirectResponse
     */
    public function delete(Request $request): RedirectResponse
    {
        $fileId = $request->input('id');

        $file = auth()->user()->files()->find($fileId);

        if (!$file) {
            return redirect()->back()->with('error', 'File not found or access denied.');
        }

        $this->unlink(config('settings.file_path.gallery.path'), $file);

        return redirect()->back()->with('success', 'Gallery file deleted successfully.');
    }

    public function download(File $file)
    {

        $location = config('settings.file_path.gallery.path');

        $response = $this->downloadFile($location, $file);

        if (!$response) {
            return redirect()->back()->with('error', 'File not found or cannot be downloaded.');
        }

        return $response;
    }

    /**
     * Quick upload for post composer - returns JSON
     */
    public function quickUpload(Request $request)
    {
        $allowedTypes = site_settings('allowed_file_types', 'jpg,jpeg,png,gif,mp4,mov,avi,webm');

        $request->validate([
            'file' => ['required', 'file', 'mimes:' . $allowedTypes, 'max:20480'],
        ]);

        $uploadedFile = $request->file('file');

        $response = $this->storeFile(
            file: $uploadedFile,
            location: config("settings.file_path.gallery.path"),
        );

        $file = $this->user->files()->create([
            'name' => $response['name'],
            'disk' => $response['disk'],
            'type' => FileKey::GALLERY_FILE->value,
            'size' => $response['size'],
            'extension' => $response['extension'],
        ]);

        // Associate with all platforms by default for quick uploads
        $allPlatforms = Platform::all();
        $pivotRows = [];
        foreach ($allPlatforms as $platform) {
            $pivotRows[] = [
                'user_id' => $this->user->id,
                'file_id' => $file->id,
                'platform_id' => $platform->id,
                'type' => getFileTypeFromExtension($file->extension),
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }
        UserFilePlatform::insert($pivotRows);

        return response()->json([
            'success' => true,
            'file' => [
                'id' => $file->id,
                'title' => $file->name,
                'type' => getFileTypeFromExtension($file->extension),
                'size' => $file->size,
                'thumbnail' => imageURL($file, 'gallery'),
                'isVideo' => (getFileTypeFromExtension($file->extension) === 'video'),
                'alt' => $file->name,
            ]
        ]);
    }
}
