<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::with('user')->orderBy('created_at', 'desc')->get();

        $orders->map(function ($order) {
            $order->files = $order->getMedia('order_files')->map(function ($media) {
                return [
                    'id' => $media->id,
                    'title' => $media->getCustomProperty('title'),
                    'file_name' => $media->file_name,
                    'mime_type' => $media->mime_type,
                    'size' => $media->size,
                    'url' => $media->getUrl(),
                ];
            });

            return $order;
        });

        return response()->json($orders);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => ['required', Rule::in(array_keys(Order::getOrderTypes()))],
            'files' => 'nullable|array',
            'files.*' => 'file|max:10240', // 10MB max
            'file_titles' => 'nullable|array',
            'file_titles.*' => 'string|max:255',
        ]);

        $order = Order::create([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'created_by' => Auth::id(),
        ]);

        if ($request->hasFile('files')) {
            $files = $request->file('files');
            $titles = $request->input('file_titles', []);

            foreach ($files as $index => $file) {
                $title = $titles[$index] ?? $file->getClientOriginalName();
                $order->addOrderFile($file, $title);
            }
        }

        return response()->json($order->load('user'), 201);
    }

    public function show(Order $order)
    {
        $order->load('user');
        $order->files = $order->getMedia('order_files')->map(function ($media) {
            return [
                'id' => $media->id,
                'title' => $media->getCustomProperty('title'),
                'file_name' => $media->file_name,
                'mime_type' => $media->mime_type,
                'size' => $media->size,
                'url' => $media->getUrl(),
            ];
        });

        return response()->json($order);
    }

    public function update(Request $request, Order $order)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => ['required', Rule::in(array_keys(Order::getOrderTypes()))],
            'files' => 'nullable|array',
            'files.*' => 'file|max:10240', // 10MB max
            'file_titles' => 'nullable|array',
            'file_titles.*' => 'string|max:255',
        ]);

        $order->update([
            'name' => $validated['name'],
            'type' => $validated['type'],
        ]);

        if ($request->hasFile('files')) {
            $files = $request->file('files');
            $titles = $request->input('file_titles', []);

            foreach ($files as $index => $file) {
                $title = $titles[$index] ?? $file->getClientOriginalName();
                $order->addOrderFile($file, $title);
            }
        }

        return response()->json($order->load('user'));
    }

    public function destroy(Order $order)
    {
        // Delete associated media files
        $order->clearMediaCollection('order_files');

        $order->delete();

        return response()->json(null, 204);
    }

    public function uploadFile(Request $request, Order $order)
    {
        $request->validate([
            'file' => 'required|file|max:10240', // 10MB max
            'title' => 'required|string|max:255',
        ]);

        $file = $request->file('file');
        $title = $request->input('title');

        $media = $order->addOrderFile($file, $title);

        return response()->json([
            'id' => $media->id,
            'title' => $media->getCustomProperty('title'),
            'file_name' => $media->file_name,
            'mime_type' => $media->mime_type,
            'size' => $media->size,
            'url' => $media->getUrl(),
        ], 201);
    }

    public function deleteFile(Order $order, $fileId)
    {
        $media = $order->getMedia('order_files')->where('id', $fileId)->first();

        if (! $media) {
            return response()->json(['error' => 'File not found'], 404);
        }

        $media->delete();

        return response()->json(null, 204);
    }

    public function updateFileTitle(Request $request, Order $order, $fileId)
    {
        $request->validate([
            'title' => 'required|string|max:255',
        ]);

        $media = $order->getMedia('order_files')->where('id', $fileId)->first();

        if (! $media) {
            return response()->json(['error' => 'File not found'], 404);
        }

        $media->setCustomProperty('title', $request->input('title'));
        $media->save();

        return response()->json([
            'id' => $media->id,
            'title' => $media->getCustomProperty('title'),
        ]);
    }
}
