<?php

namespace Modules\Lpj\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use Modules\Lpj\Models\Debiture;

/**
 * Controller untuk API pencarian debitur
 * Digunakan untuk autocomplete search pada form pembayaran
 */
class DebiturController extends Controller
{
    /**
     * Pencarian debitur untuk autocomplete
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function search(Request $request): JsonResponse
    {
        try {
            // Log aktivitas pencarian
            Log::info('API Debitur Search - Request', [
                'query' => $request->get('q'),
                'user_id' => Auth::id()
            ]);

            $query = $request->get('q', '');

            // Validasi minimal 2 karakter untuk pencarian
            if (strlen($query) < 2) {
                return response()->json([
                    'success' => false,
                    'message' => 'Minimal 2 karakter untuk pencarian',
                    'data' => []
                ], 400);
            }

            // Mulai database transaction
            DB::beginTransaction();

            try {
                // Query pencarian debitur
                // Asumsi tabel debitur dengan kolom: id, code, nama, alamat
                $debiturs = Debiture::query()
                    ->select('id', 'cif', 'name', 'address')
                    ->whereAny(['cif','name'], 'LIKE', "%{$query}%")
                    ->orderBy('name', 'asc')
                    ->limit(20) // Batasi hasil maksimal 20
                    ->get();

                // Format data untuk TomSelect
                $formattedData = $debiturs->map(function($debitur) {
                    return [
                        'id' => $debitur->id,
                        'kode_debitur' => $debitur->cif,
                        'name' => $debitur->name,
                        'address' => $debitur->address
                    ];
                });

                DB::commit();

                // Log hasil pencarian
                Log::info('API Debitur Search - Success', [
                    'query' => $query,
                    'results_count' => $formattedData->count(),
                    'user_id' => Auth::id()
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Data debitur berhasil ditemukan',
                    'data' => $formattedData
                ]);

            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }

        } catch (Exception $e) {
            // Log error
            Log::error('API Debitur Search - Error', [
                'query' => $request->get('q'),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat mencari data debitur',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }

    /**
     * Get detail debitur berdasarkan code
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getByCode(Request $request): JsonResponse
    {
        try {
            $code = $request->get('code');

            if (empty($code)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Code debitur harus diisi',
                    'data' => null
                ], 400);
            }

            // Log aktivitas get detail
            Log::info('API Debitur GetByCode - Request', [
                'code' => $code,
                'user_id' => Auth::id()
            ]);

            DB::beginTransaction();

            try {
                $debitur = DB::table('debitur')
                    ->select('id', 'code', 'nama', 'alamat', 'telepon', 'email')
                    ->where('code', $code)
                    ->where('status', 'aktif')
                    ->first();

                if (!$debitur) {
                    DB::rollback();
                    return response()->json([
                        'success' => false,
                        'message' => 'Debitur tidak ditemukan',
                        'data' => null
                    ], 404);
                }

                DB::commit();

                Log::info('API Debitur GetByCode - Success', [
                    'code' => $code,
                    'debitur_id' => $debitur->id,
                    'user_id' => Auth::id()
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Data debitur berhasil ditemukan',
                    'data' => $debitur
                ]);

            } catch (Exception $e) {
                DB::rollback();
                throw $e;
            }

        } catch (Exception $e) {
            Log::error('API Debitur GetByCode - Error', [
                'code' => $request->get('code'),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => Auth::id()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Terjadi kesalahan saat mengambil data debitur',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal Server Error'
            ], 500);
        }
    }
}
