<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Modules\Admin\app\Models\Document;

class DocumentController extends Controller
{
    use HasOrderByRequest;
    use HasFilterRequest;
    use HasSearchRequest;
    
    public function all(Request $request)
    {
        $documents = new Document;

        // Order by
        $this->orderByRequest($documents, $request);
        $documents->orderBy('title', 'asc');
        // Filter
        $this->filterRequest(
            builder: $documents,
            request: $request,
            filterKeys: [
                'title' => self::F_TEXT,
            ]
        );
        $this->searchRequest(
            builder: $documents,
            value: $request->get('search'),
            fields: [
                'title',
            ]
        );

        $responseData = $documents->get();
        return AbstractController::ResultSuccess($responseData);
    }

    public function create(Request $request)
    {
        $request->validate([
            'type' => 'required|in:file,link',
            'files' => 'nullable|array',
            'files.*.title' => 'required|string|max:255',
            'files.*.file' => 'required|file|mimes:doc,docx,xls,xlsx,pdf|max:20480',
            'links' => 'nullable|array',
            'links.*.title' => 'required|string|max:255',
            'links.*.uri' => 'required|string|url',
            'is_active' => 'required|boolean',
        ]);

        $documents = [];
        
        if ($request->type === "file") {
            foreach ($request->file('files') as $index => $file) {
                $path = $file['file']->store('uploads', 'public');
                $documents[] = [
                    'title' => $request->input("files.$index.title"),
                    'type' => 'file',
                    'uri' => "storage/{$path}",
                    'is_active' => $request->is_active,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        } else {
            foreach ($request->links as $link) {
                $documents[] = [
                    'title' => $link['title'],
                    'type' => 'link',
                    'uri' => $link['uri'],
                    'is_active' => $request->is_active,
                    'created_at' => now(),
                    'updated_at' => now(),
                ];
            }
        }

        if (!empty($documents)) {
            Document::insert($documents);
        }

        return AbstractController::ResultSuccess($documents, "Documents created successfully!");
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:documents,id',
            'title' => 'required|string|max:255',
            'type' => 'required|in:file,link',
            'uri'   => 'nullable|url',
            'file' => 'nullable|file|mimes:doc,docx,xls,xlsx,pdf|max:20480',
            'existing_file' => 'nullable|string',
            'is_active' => 'required|boolean',
        ]);

        $document = Document::find($request->input('id'));
        if (!$document) {
            return AbstractController::ResultError("Document not found.");
        }

        if ($request->type === "file") {
            $uri = $request->existing_file;

            if ($request->hasFile('file')) {
                $filePath = str_replace('storage/', 'public/', $request->existing_file);
                if (Storage::exists($filePath)) {
                    Storage::delete($filePath);
                }

                $path = $request->file('file')->store('uploads', 'public');
                $uri = "storage/{$path}";
            }

            $document->update([
                'title' => $request->title,
                'type' => $request->type,
                'uri' => $uri,
                'is_active' => $request->is_active,
            ]);

            return AbstractController::ResultSuccess($document, "Document updated successfully!");
        }

        $document->update([
            'title' => $request->title,
            'type' => $request->type,
            'uri' =>  $request->uri,
            'is_active' => $request->is_active,
        ]);

        return AbstractController::ResultSuccess($document, "Document updated successfully!");
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $document = Document::find($id);
        if (!$document) {
            return AbstractController::ResultError("Document not found");
        }

        if ($document->type === "file") {
            $filePath = str_replace('storage/', 'public/', $document->uri);
            if (Storage::exists($filePath)) {
                Storage::delete($filePath);
            }
        }

        $document->delete();
        return AbstractController::ResultSuccess("Document deleted successfully!");
    }
}
