<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DocumentLibrary;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class DocumentLibraryController extends Controller
{

 

public function store(Request $request)
{
    DB::beginTransaction();

    try {

        $validator = Validator::make($request->all(), [
            'Fnc_Id' => 'nullable|integer',
            'Rec_Id' => 'required|integer',
            'documents' => 'required|array',
            'documents.*' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => $validator->errors()
            ], 422);
        }

        $savedDocs = [];
        $serial = 1;

        foreach ($request->documents as $index => $doc) {

            $filePath = null;
            $description = $doc['name'] ?? null;

            $folderName = 'budget_documents';
            $folderPath = public_path($folderName);

            if (!File::exists($folderPath)) {
                File::makeDirectory($folderPath, 0755, true, true);
            }


            if (isset($doc['file']) && str_contains($doc['file'], 'base64')) {

                preg_match("/data:(.*?);base64,(.*)/", $doc['file'], $matches);

                $ext = explode('/', $matches[1])[1] ?? 'jpg';

                $fileName = Str::uuid() . '.' . $ext;

                file_put_contents(
                    $folderPath . '/' . $fileName,
                    base64_decode($matches[2])
                );

                
                $filePath = url($folderName . '/' . $fileName);
            }

           
            if ($request->hasFile("documents.$index.file")) {

                $file = $request->file("documents.$index.file");

                $fileName = Str::uuid() . '.' . $file->getClientOriginalExtension();

                $file->move($folderPath, $fileName);

                $filePath = url($folderName . '/' . $fileName);
            }

            
            if (!$filePath && isset($doc['file'])) {

                
                if (str_contains($doc['file'], 'http')) {
                    $filePath = $doc['file'];
                } else {
                    $filePath = url($doc['file']);
                }
            }

            $docRow = DocumentLibrary::create([
                'Fnc_Id' => $request->Fnc_Id,
                'Rec_Id' => $request->Rec_Id,
                'Description' => $description,
                'Doc_Upload' => $filePath, 
                'Serial_No' => $serial++
            ]);

            $savedDocs[] = $docRow;
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Documents uploaded successfully',
            'data' => $savedDocs
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Upload failed',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}

    

    public function getByRecord($fncId, $recId)
    {
        $docs = DocumentLibrary::where('Fnc_Id', $fncId)
            ->where('Rec_Id', $recId)
            ->get()
            ->map(function ($doc) {

                return [
                    'Doc_Lib' => $doc->Doc_Lib,
                    'Fnc_Id' => $doc->Fnc_Id,
                    'Rec_Id' => $doc->Rec_Id,
                    'Description' => $doc->Description,
                    'Doc_Upload' => url($doc->Doc_Upload),
                    'Serial_No' => $doc->Serial_No,
                    'created_at' => $doc->created_at
                ];
            });

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


   

public function destroy($id)
{
    try {

        $doc = DocumentLibrary::find($id);

        if (!$doc) {
            return response()->json([
                'success' => false,
                'message' => 'Document not found'
            ], 404);
        }

        if ($doc->Doc_Upload) {

            $relativePath = ltrim($doc->Doc_Upload, '/');

            $fullPath = public_path($relativePath);

            if (file_exists($fullPath)) {
                unlink($fullPath);
            }
        }

        $doc->delete();

        return response()->json([
            'success' => true,
            'message' => 'Document deleted successfully'
        ]);

    } catch (\Exception $e) {

        return response()->json([
            'success' => false,
            'message' => 'Delete failed',
            'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
        ], 500);
    }
}


    public function index()
    {
        $docs = DocumentLibrary::latest()->paginate(20);

        $docs->getCollection()->transform(function ($doc) {

            $doc->Doc_Upload = url($doc->Doc_Upload);

            return $doc;
        });

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

}
