<?php

namespace App\Http\Controllers;

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

class WorkBGTransController extends Controller
{

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

    $query = WorkBGTrans::with([
            'subledger',
            'workAllocation',
            'workAllocation.tender',
            'noc',
            'hod'
        ])
        ->orderBy('WBT_Id', 'desc');

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

            // 🔹 Main Table Search
            $q->where('WBT_Type', 'like', "%{$search}%")
              ->orWhere('BG_Amt', 'like', "%{$search}%")
              ->orWhere('WBT_CD', 'like', "%{$search}%")
              ->orWhere('WBT_BillNo', 'like', "%{$search}%")
              ->orWhere('Remarks', 'like', "%{$search}%")
              ->orWhere('Status', 'like', "%{$search}%");

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

            // 🔹 Subledger Search
            $q->orWhereHas('subledger', function ($subQ) use ($search) {
                $subQ->where('SL_Code', 'like', "%{$search}%")
                     ->orWhere('SL_Name', 'like', "%{$search}%")
                     ->orWhere('SL_Address', 'like', "%{$search}%")
                     ->orWhere('SL_City', 'like', "%{$search}%")
                     ->orWhere('SL_Phone', 'like', "%{$search}%")
                     ->orWhere('SL_Email', 'like', "%{$search}%")
                     ->orWhere('PAN_Number', 'like', "%{$search}%")
                     ->orWhere('GSTIN', 'like', "%{$search}%")
                     ->orWhere('Account_Number', 'like', "%{$search}%")
                     ->orWhere('IFSC_Code', 'like', "%{$search}%");
            });

            // 🔹 Work Allocation
            $q->orWhereHas('workAllocation', function ($subQ) use ($search) {
                $subQ->where('WA_RefId', 'like', "%{$search}%")
                     ->orWhere('WO_Amount', 'like', "%{$search}%");
            });

            // 🔹 NOC
            $q->orWhereHas('noc', function ($subQ) use ($search) {
                $subQ->where('WNE_RefId', 'like', "%{$search}%");
            });

            // 🔹 HOD
            $q->orWhereHas('hod', function ($subQ) use ($search) {
                $subQ->where('HOD_Name', 'like', "%{$search}%");
            });

        });
    }

    // ✅ Exact Status Filter
    if ($request->filled('Status')) {
        $query->where('Status', $request->Status);
    }
     if ($request->filled('WBT_Type')) {
        $query->where('WBT_Type', $request->WBT_Type);
    }

    $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($id)
    {
        $record = WorkBGTrans::with([
            'subledger',
            'workAllocation',
            'workAllocation.tender',
            'noc',
            'hod'
        ])->findOrFail($id);

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


    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [

            'WBT_Date' => 'nullable|date',

            'WBT_Type' => 'required|in:Receipt,Release,Adjust,Forefeight',

            'SL_Id'  => 'required|exists:subledg_master,SL_Id',
            'WA_Id'  => 'required|exists:work_allocation_book,WA_Id',
            'WNE_Id' => 'nullable|exists:wonoc_entry,WNE_Id',

            'BG_Amt' => 'nullable|numeric|min:0',

            'WBT_HOD' => 'nullable|exists:user_master,Usr_Id',

            'WBT_CD'     => 'nullable|string|max:100',
            'WBT_BillNo' => 'nullable|string|max:100',
                'Status'  => 'nullable|in:draft,hod_app,hod_rej',
        'Remarks' => 'nullable|string',

        ]);

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

        DB::beginTransaction();

        try {

            $data = $request->all();

            // Auto timestamp when HOD present
            if (!empty($request->WBT_HOD)) {
                $data['WBT_HDT'] = now();
            }

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

            DB::commit();

            $record->load(['subledger','workAllocation','noc','hod']);

            return response()->json([
                'success' => true,
                'message' => 'BG 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 = WorkBGTrans::findOrFail($id);

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

        'WBT_Date' => 'sometimes|nullable|date',

        'WBT_Type' => 'sometimes|nullable|in:Receipt,Release,Adjust,Forefeight',

        'SL_Id'  => 'sometimes|nullable|exists:subledg_master,SL_Id',
        'WA_Id'  => 'sometimes|nullable|exists:work_allocation_book,WA_Id',
        'WNE_Id' => 'sometimes|nullable|exists:wonoc_entry,WNE_Id',

        'BG_Amt' => 'sometimes|nullable|numeric|min:0',

        'WBT_HOD' => 'sometimes|nullable|exists:user_master,Usr_Id',

        'WBT_CD'     => 'nullable|string|max:100',
        'WBT_BillNo' => 'nullable|string|max:100',

        // ✅ NEW
        'Status'  => 'sometimes|in:draft,hod_app,hod_rej',
        '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('WBT_HOD') && !empty($request->WBT_HOD)) {
            $data['WBT_HDT'] = now();
        }

        // Auto timestamp when approved or rejected
        if ($request->has('Status') && in_array($request->Status, ['hod_app','hod_rej'])) {
            $data['WBT_HDT'] = now();
        }

        $record->update($data);

        DB::commit();

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

        return response()->json([
            'success' => true,
            'message' => 'BG 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 = WorkBGTrans::findOrFail($id);
        $record->delete();

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



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

    $query = WorkBGTrans::with([
        'subledger',
        'workAllocation',
        'workAllocation.tender',
        'noc',
        'hod'
    ])->orderBy('WBT_Id','desc');

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

            $q->where('WBT_Type', 'like', "%{$search}%")
              ->orWhere('BG_Amt', 'like', "%{$search}%")
              ->orWhere('WBT_CD', 'like', "%{$search}%")
              ->orWhere('WBT_BillNo', 'like', "%{$search}%")
              ->orWhere('Remarks', 'like', "%{$search}%")
              ->orWhere('Status', 'like', "%{$search}%");

            if (strtotime($search)) {
                $q->orWhereDate('WBT_Date', '=', $search);
            }

            $q->orWhereHas('subledger', function ($subQ) use ($search) {
                $subQ->where('SL_Code', 'like', "%{$search}%")
                     ->orWhere('SL_Name', 'like', "%{$search}%")
                     ->orWhere('SL_City', 'like', "%{$search}%")
                     ->orWhere('PAN_Number', 'like', "%{$search}%")
                     ->orWhere('GSTIN', 'like', "%{$search}%");
            });

            $q->orWhereHas('workAllocation', function ($subQ) use ($search) {
                $subQ->where('WA_RefId', 'like', "%{$search}%");
            });

        });
    }

         if ($request->filled('WBT_Type')) {
        $query->where('WBT_Type', $request->WBT_Type);
    }


    if ($request->filled('Status')) {
        $query->where('Status', $request->Status);
    }

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


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

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

    DB::beginTransaction();

    try {

        WorkBGTrans::whereIn('WBT_Id', $request->ids)
            ->update([
                'WBT_CD' => $request->WBT_CD,
                'WBT_Type' => 'Release'
            ]);

        DB::commit();

        return response()->json([
            'success' => true,
            'message' => 'WBT_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);
    }
}
}
