<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class FileStoreController extends Controller
{
    public function attachFiles(Request $request)
    {
        if (!$request->hasFile('file')) {
            return response()->json(['error' => 'No file'], 400);
        }

        $file      = $request->file('file');
        $orderId   = $request->input('order_id');
        $orderType = $request->input('order_type', 'auto_');
        $fileType  = $request->input('file_type', 'additional');

        $ext      = strtolower($file->getClientOriginalExtension());
        $name     = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $filename = Str::uuid() . '.' . $ext;
        $path     = $file->storeAs('public/files/' . $orderType . $orderId, $filename);
        $size     = $file->getSize();

        DB::table('files')->insert([
            'id'            => (string) Str::uuid(),
            'path'          => Storage::url($path),
            'extension'     => $ext,
            'order_id'      => $orderId,
            'order_type'    => $orderType,
            'type'          => $fileType,
            'name'          => $name,
            'size'          => round($size / 1024 / 1024, 2),
            'size_in_bytes' => $size,
            'created_at'    => now(),
            'updated_at'    => now(),
        ]);

        return response()->json(['success' => true, 'name' => $name]);
    }

    public function attachProfileFiles(Request $request)
    {
        if (!$request->hasFile('file')) {
            return response()->json(['error' => 'No file'], 400);
        }

        $file     = $request->file('file');
        $ext      = strtolower($file->getClientOriginalExtension());
        $filename = Str::uuid() . '.' . $ext;
        $path     = $file->storeAs('public/files/profile', $filename);

        return response()->json(['success' => true, 'url' => Storage::url($path)]);
    }

    public function downloadFile($file)
    {
        $record = DB::table('files')->where('id', $file)->first();
        if (!$record) abort(404);

        $path = str_replace('/storage/', 'public/', $record->path);
        if (!Storage::exists($path)) abort(404);

        return Storage::download($path, $record->name . '.' . $record->extension);
    }

    public function delete($file)
    {
        $record = DB::table('files')->where('id', $file)->first();
        if ($record) {
            $path = str_replace('/storage/', 'public/', $record->path);
            Storage::delete($path);
            DB::table('files')->where('id', $file)->delete();
        }
        return redirect()->back();
    }
}
