<?php

namespace App\Http\Controllers;

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

class VendTdsCnsptnController extends Controller
{

    // ✅ INDEX (Search + Pagination)
   public function index(Request $request)
{
    $perPage = $request->get('per_page', 10);
    $search  = $request->get('search');

    $slId     = $request->get('SL_Id');
    $tdsRate  = $request->get('TDS_rate');
    $isActive = $request->get('Is_Active', 'Y'); // ✅ default Y

    $query = VendTdsCnsptn::with(['subLedger', 'financialYear']);

    // 🔍 SEARCH
    if (!empty($search)) {
        $query->where(function ($q) use ($search) {
            $q->where('TDS_rate', 'like', "%$search%")
              ->orWhere('Remark', 'like', "%$search%");

            // ✅ numeric search for SL_Id
            if (is_numeric($search)) {
                $q->orWhere('SL_Id', $search);
            }
        });
    }

    // 🎯 FILTERS
    if (!empty($slId)) {
        $query->where('SL_Id', $slId);
    }

    if (!empty($tdsRate)) {
        $query->where('TDS_rate', $tdsRate);
    }

    // ✅ Active filter
    if (!empty($isActive)) {
        $query->where('Is_Active', $isActive);
    }

    $data = $query->orderBy('VTC_Id', 'desc')->paginate($perPage);

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

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

    try {

        $validator = Validator::make($request->all(), [

            'SL_Id' => 'required|exists:subledg_master,SL_Id',
            'FY_Id' => 'required|exists:fyear_master,FY_Id',
            'VTC_Date' => 'nullable|date',
            'TDS_rate' => 'required|string|max:2',
            'Remark' => 'nullable|string',
            'Is_Active' => 'nullable|in:Y,N',
            'Fnc_Id' => 'nullable|exists:function_types,Fnc_Id',

            'Documents' => 'nullable|array',
            'Documents.*' => 'file',
            'Documents_description' => 'nullable|array',
        ]);

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

        // ✅ CREATE ENTRY
        $entry = VendTdsCnsptn::create([
            'SL_Id' => $request->SL_Id,
            'FY_Id' => $request->FY_Id,
            'VTC_Date' => $request->VTC_Date,
            'TDS_rate' => $request->TDS_rate,
            'Remark' => $request->Remark,
            'Is_Active' => $request->Is_Active ?? 'Y',
            'Document' => [] // 🔥 array
        ]);

        $newDocs = [];

        if ($request->hasFile('Documents')) {

            foreach ($request->file('Documents') as $index => $file) {

                if (!$file->isValid()) continue;

                $folder = 'tds_documents';
                $path = public_path($folder);

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

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

                $url = url($folder . '/' . $fileName);

                $description = $request->Documents_description[$index] ?? null;

                // ✅ document_library
                $doc = DocumentLibrary::create([
                    'Fnc_Id' => $request->Fnc_Id,
                    'Rec_Id' => $entry->VTC_Id,
                    'Description' => $description,
                    'Doc_Upload' => $url,
                    'Serial_No' => $index + 1
                ]);

                $newDocs[] = [
                    'doc_lib_id' => $doc->Doc_Lib,
                    'name' => 'Document_' . ($index + 1),
                    'description' => $description,
                    'url' => $url
                ];
            }
        }

        // ✅ SAVE ARRAY DIRECTLY
        if (!empty($newDocs)) {
            $entry->update([
                'Document' => $newDocs
            ]);
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Created successfully',
            'data' => $entry
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}

    // ✅ SHOW
    public function show($id)
    {
        $data = VendTdsCnsptn::with(['subLedger', 'financialYear'])
            ->findOrFail($id);

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

public function update(Request $request, $id)
{
    DB::beginTransaction();

    try {

        $entry = VendTdsCnsptn::find($id);

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

        $validator = Validator::make($request->all(), [

            'SL_Id' => 'sometimes|exists:subledg_master,SL_Id',
            'FY_Id' => 'sometimes|exists:fyear_master,FY_Id',
            'VTC_Date' => 'nullable|date',
            'TDS_rate' => 'sometimes|string|max:2',
            'Remark' => 'nullable|string',
            'Is_Active' => 'sometimes|in:Y,N',
            'Fnc_Id' => 'nullable|exists:function_types,Fnc_Id',

            'Documents' => 'nullable|array',
            'Documents.*' => 'nullable|string',
            'Documents_description' => 'nullable|array',
        ]);

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

        // ✅ update fields
        $entry->update($request->except('Documents', 'Documents_description'));

        $existingDocs = $entry->Document ?? [];
        $newDocs = [];

        $fncId = $request->Fnc_Id ?? null;

        // ✅ BASE64 upload
        if (!empty($request->Documents)) {

            foreach ($request->Documents as $index => $base64) {

                if (!$base64) continue;

                if (strpos($base64, 'base64,') !== false) {

                    [$meta, $content] = explode(',', $base64);

                    preg_match('/data:(.*?);base64/', $meta, $matches);
                    $ext = isset($matches[1]) ? explode('/', $matches[1])[1] : 'png';

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

                    $folder = 'tds_documents';
                    $path = public_path($folder);

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

                    file_put_contents($path . '/' . $fileName, base64_decode($content));

                    $url = url($folder . '/' . $fileName);

                    $description = $request->Documents_description[$index] ?? null;

                    $serial = count($existingDocs) + count($newDocs) + 1;

                    // ✅ document_library
                    $doc = DocumentLibrary::create([
                        'Fnc_Id' => $fncId,
                        'Rec_Id' => $entry->VTC_Id,
                        'Description' => $description,
                        'Doc_Upload' => $url,
                        'Serial_No' => $serial
                    ]);

                    $newDocs[] = [
                        'doc_lib_id' => $doc->Doc_Lib,
                        'name' => 'Document_' . $serial,
                        'description' => $description,
                        'url' => $url
                    ];
                }
            }
        }

        // ✅ merge array directly
        if (!empty($newDocs)) {

            $entry->update([
                'Document' => array_merge($existingDocs, $newDocs)
            ]);
        }

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'Updated successfully',
            'data' => $entry
        ]);

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}

    // ✅ DELETE
    public function destroy($id)
    {
        $data = VendTdsCnsptn::findOrFail($id);
        $data->delete();

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


    public function deleteDocument($docLibId)
{
    DB::beginTransaction();

    try {

        // ✅ find document
        $doc = DocumentLibrary::find($docLibId);

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

        // ✅ find main entry
        $entry = VendTdsCnsptn::find($doc->Rec_Id);

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

        // ✅ delete file from folder
        if ($doc->Doc_Upload) {

            $filePath = public_path(parse_url($doc->Doc_Upload, PHP_URL_PATH));

            if (File::exists($filePath)) {
                File::delete($filePath);
            }
        }

        // ✅ remove from JSON column
        $existingDocs = $entry->Document ?? [];

        $updatedDocs = array_values(array_filter($existingDocs, function ($item) use ($docLibId) {
            return $item['doc_lib_id'] != $docLibId;
        }));

        $entry->update([
            'Document' => $updatedDocs
        ]);

        // ✅ delete from document_library
        $doc->delete();

        DB::commit();

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

    } catch (\Exception $e) {

        DB::rollBack();

        return response()->json([
            'success' => false,
            'message' => 'Something went wrong. Please try again later.'
        ], 500);
    }
}
}
