<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Response;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class StorageController extends Controller
{
    public function serve(Request $request, $file_path)
    {
        $allowed_directory = 'uploads';
        $file_path = str_replace(['../', '..\\'], '', $file_path);
        $full_path = storage_path("app/{$allowed_directory}/{$file_path}");

        if (is_dir($full_path)) {
            throw new NotFoundHttpException('檔案不存在');
        }
        
        if (!Storage::disk('local')->exists("{$allowed_directory}/{$file_path}")) {
            throw new NotFoundHttpException('檔案不存在');
        }
        
        $real_path = realpath($full_path);
        $allowed_base_path = realpath(storage_path("app/{$allowed_directory}"));
        if (!$real_path || strpos($real_path, $allowed_base_path) !== 0) {
            throw new AccessDeniedHttpException('無權訪問該檔案');
        }
        $mime_type = mime_content_type($full_path) ?: 'application/octet-stream';
        return Response::file($full_path, [
            'Content-Type' => $mime_type,
            'Content-Disposition' => 'inline; filename="' . basename($file_path) . '"',
            'X-Frame-Options' => 'SAMEORIGIN', // Allow same-origin framing
            'Content-Security-Policy' => "frame-ancestors 'self'", // Allow iframe on same domain
        ]);
    }

    public function imageRotation90(Request $request, $file_path)
    {
        $allowed_directory = 'uploads';
        $file_path = str_replace(['../', '..\\'], '', $file_path);
        $full_path = storage_path("app/{$allowed_directory}/{$file_path}");

        if (is_dir($full_path)) {
            throw new NotFoundHttpException('檔案不存在');
        }
        
        if (!Storage::disk('local')->exists("{$allowed_directory}/{$file_path}")) {
            throw new NotFoundHttpException('檔案不存在');
        }
        
        $real_path = realpath($full_path);
        $allowed_base_path = realpath(storage_path("app/{$allowed_directory}"));
        if (!$real_path || strpos($real_path, $allowed_base_path) !== 0) {
            throw new AccessDeniedHttpException('無權訪問該檔案');
        }
        $mime_type = mime_content_type($full_path) ?: 'application/octet-stream';

        $allowedMimeTypes = [
                'image/png',      // PNG
                'image/jpeg',     // JPG/JPEG
                'image/git' // git
            ];

        if (!in_array($mime_type, $allowedMimeTypes)) {
            throw new \Exception('檔案類型錯誤，只接受.jpg/.jpeg/.png/.gif');
        }

        $manager = new ImageManager(Driver::class);
        $image = $manager->read($full_path);
        $image = $image->rotate(-90);
        $image->save(quality:100);

        return [];
    }
}
