<?php

namespace App\Http\Controllers;

use App\Models\TndEMDTrans;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class TndEMDTransController extends Controller
{

    // public function index(Request $request)
    // {
    //     $perPage = $request->input('per_page', 15);
    //     $search  = trim($request->input('search', ''));

    //     $query = TndEMDTrans::with(['subledger', 'tender', 'hod',  'statusAction'])
    //         ->orderBy('TET_Id', 'desc');

    //     if (!empty($search)) {
    //         $query->where(function ($q) use ($search) {

    //             // ðŸ”¹ Main Table Search
    //             $q->where('TET_CD', 'like', "%{$search}%")
    //                 ->orWhere('TET_BillNo', 'like', "%{$search}%")
    //                 ->orWhere('EMD_Amt', 'like', "%{$search}%")
    //                 ->orWhere('Remarks', 'like', "%{$search}%");

    //             // ðŸ”¹ Date exact match (if date format matches)
    //             if (strtotime($search)) {
    //                 $q->orWhereDate('TES_Date', '=', $search)
    //                     ->orWhereDate('TER_Date', '=', $search);
    //             }

    //             // ðŸ”¹ Subledger Relation Search
    //             $q->orWhereHas('subledger', function ($subQ) use ($search) {
    //                 $subQ->where('SL_Code', 'like', "%{$search}%")
    //                     ->orWhere('SL_Name', 'like', "%{$search}%")
    //                     ->orWhere('SL_Address', 'like', "%{$search}%");
    //             });
    //         });
    //     }


    //     $data = $query->paginate($perPage);

    //     return response()->json([
    //         'success' => true,
    //         'data'    => $data->items(),
    //         'meta'    => [
    //             'current_page' => $data->currentPage(),
    //             'last_page'    => $data->lastPage(),
    //             'per_page'     => $data->perPage(),
    //             'total'        => $data->total(),
    //         ]
    //     ]);
    // }
    public function index(Request $request)
{
    $perPage = $request->input('per_page', 15);
    $search  = trim($request->input('search', ''));
    $actId   = $request->input('Act_Id'); // 👈 add this

    $query = TndEMDTrans::with(['subledger', 'tender', 'hod', 'statusAction'])
        ->orderBy('TET_Id', 'desc');

    // ✅ Act_Id Filter
    if (!empty($actId)) {
        $query->where('status', $actId);
    }

    // ✅ Search Filter
    if (!empty($search)) {
        $query->where(function ($q) use ($search) {

            // 🔹 Main Table Search
            $q->where('TET_CD', 'like', "%{$search}%")
              ->orWhere('TET_BillNo', 'like', "%{$search}%")
              ->orWhere('EMD_Amt', 'like', "%{$search}%")
              ->orWhere('Remarks', 'like', "%{$search}%");

            // 🔹 Date exact match
            if (strtotime($search)) {
                $q->orWhereDate('TES_Date', '=', $search)
                  ->orWhereDate('TER_Date', '=', $search);
            }

            // 🔹 Subledger Relation Search
            $q->orWhereHas('subledger', function ($subQ) use ($search) {
                $subQ->where('SL_Code', 'like', "%{$search}%")
                     ->orWhere('SL_Name', 'like', "%{$search}%")
                     ->orWhere('SL_Address', 'like', "%{$search}%");
            });
        });
    }

    $data = $query->paginate($perPage);

    return response()->json([
        'success' => true,
        'data'    => $data->items(),
        'meta'    => [
            'current_page' => $data->currentPage(),
            'last_page'    => $data->lastPage(),
            'per_page'     => $data->perPage(),
            'total'        => $data->total(),
        ]
    ]);
}
    public function show(Request $request, $id)
    {
        $query = TndEMDTrans::with(['subledger', 'tender', 'hod',  'statusAction'])
            ->where('TET_Id', $id);

        // âœ… Optional Status Filter
        if ($request->filled('Status')) {
            $query->where('Status', $request->Status);
        }

        $record = $query->firstOrFail();

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


    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'TE_Date' => 'nullable|date',
            'TES_Date' => 'required|date',
            'TEE_Date' => 'nullable|date',
            'For_Acc' => 'nullable|in:YES,NO',

            'TER_Date' => 'nullable|date',

            'SL_Id'    => 'required|exists:subledg_master,SL_Id',
            'TE_Id'    => 'required|exists:tender_entry,TE_Id',
            'EMD_Amt'  => 'required|numeric|min:0',
            'TET_HOD'  => 'nullable|exists:user_master,Usr_Id',

            'TET_HDT'     => 'nullable|date',
            'TET_CD'      => 'nullable|string|max:100',
            'TET_BillNo'  => 'nullable|string|max:100',
            'Status' => 'nullable|exists:action_master,Act_Id',
            'Remarks' => 'nullable|string',

        ]);

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

        DB::beginTransaction();

        try {
            $data = $request->all();

            // âœ… set default YES if not provided
            $data['For_Acc'] = $request->For_Acc ?? 'YES';

            $record = TndEMDTrans::create($data);

            DB::commit();

            $record->load(['subledger', 'tender', 'hod',  'statusAction']);

            return response()->json([
                'success' => true,
                'message' => 'EMD Transaction created successfully',
                'data' => $record
            ], 201);
        } catch (\Exception $e) {

            DB::rollBack();

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



    public function update(Request $request, $id)
    {
        $record = TndEMDTrans::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'TE_Date' => 'sometimes|nullable|date', // âœ… ADD
            'TES_Date' => 'sometimes|nullable|date',
            'TEE_Date' => 'sometimes|nullable|date',
            'For_Acc'  => 'sometimes|in:YES,No',
            'TER_Date' => 'sometimes|nullable|date', // âœ… ADD

            'SL_Id'    => 'sometimes|nullable|exists:subledg_master,SL_Id',
            'TE_Id'    => 'sometimes|nullable|exists:tender_entry,TE_Id',
            'EMD_Amt'  => 'sometimes|nullable|numeric|min:0',
            'TET_HOD'  => 'sometimes|nullable|exists:user_master,Usr_Id',
            'TET_HDT'     => 'nullable|date',
            'TET_CD'      => 'nullable|string|max:100',
            'TET_BillNo'  => 'nullable|string|max:100',
            'Status' => 'sometimes|nullable|exists:action_master,Act_Id',
            'Remarks' => 'sometimes|nullable|string',

        ]);

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

        DB::beginTransaction();

        try {

            $data = $request->all();



            // âœ… AUTO TIMESTAMP WHEN HOD SENT
            if ($request->has('TET_HOD') && !empty($request->TET_HOD)) {
                $data['TET_HDT'] = now();
            }

            $record->update($data);

            DB::commit();

            $record->refresh()->load(['subledger', 'tender', 'hod']);

            return response()->json([
                'success' => true,
                'message' => 'EMD Transaction updated successfully',
                'data' => $record
            ]);
        } catch (\Exception $e) {

            DB::rollBack();

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



    public function destroy($id)
    {
        $record = TndEMDTrans::findOrFail($id);
        $record->delete();

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



    public function getAll(Request $request)
    {
        $search = trim($request->input('search', ''));

        $query = TndEMDTrans::with(['subledger', 'tender', 'hod',  'statusAction'])
            ->orderBy('TET_Id', 'desc');

        // ðŸ”Ž Search Filter
        if (!empty($search)) {
            $query->where(function ($q) use ($search) {

                // ðŸ”¹ Main Table Search
                $q->where('TET_CD', 'like', "%{$search}%")
                    ->orWhere('TET_BillNo', 'like', "%{$search}%")
                    ->orWhere('EMD_Amt', 'like', "%{$search}%")
                    ->orWhere('Remarks', 'like', "%{$search}%");

                // ðŸ”¹ Date exact match
                if (strtotime($search)) {
                    $q->orWhereDate('TES_Date', '=', $search)
                        ->orWhereDate('TER_Date', '=', $search);
                }

                // ðŸ”¹ Subledger Relation Search
                $q->orWhereHas('subledger', function ($subQ) use ($search) {
                    $subQ->where('SL_Code', 'like', "%{$search}%")
                        ->orWhere('SL_Name', 'like', "%{$search}%")
                        ->orWhere('SL_Address', 'like', "%{$search}%");
                });
            });
        }


        $data = $query->get();

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

    public function bulkCDUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'ids' => 'required|array|min:1',
            'ids.*' => 'exists:tndemd_trans,TET_Id',
            'TET_CD' => 'required|in:Credit,Debit'
        ]);


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


        DB::beginTransaction();


        try {


            TndEMDTrans::whereIn('TET_Id', $request->ids)
                ->update([
                    'TET_CD' => $request->TET_CD
                ]);


            DB::commit();


            return response()->json([
                'success' => true,
                'message' => 'TET_CD updated successfully for selected records'
            ]);
        } catch (\Exception $e) {


            DB::rollBack();


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