<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Agent;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class AgentController extends Controller
{
    public function index(Request $request)
    {
        $query = DB::table('ADMIN_SKT.TM_AGEN AS A')
            ->leftJoin('ADMIN_SKT.D_KTR AS K', 'A.KTR_ADMINISTRASI', '=', 'K.KDKTR')
            ->leftJoin('ADMIN_SKT.RF_JABATAN_AGEN AS J', 'A.KD_JABATAN_AGEN', '=', 'J.KD_JABATAN')
            ->select(
                'A.NO_AGEN',
                'A.NAMA',
                'J.SINGKATAN_JABATAN',
                'K.KDKTR',
                'K.NMKTR',
                DB::raw("TO_CHAR(A.TGL_LISENSI_AKHIR, 'DD-MM-YYYY') AS TGL_LISENSI_AKHIR")
            );

        // Filter based on search input
        if ($request->filled('no_agen')) {
            $query->where('A.NO_AGEN', 'like', '%' . $request->input('no_agen') . '%');
        }
        if ($request->filled('nama')) {
            $query->where(DB::raw('LOWER(A.NAMA)'), 'like', '%' . strtolower($request->input('nama')) . '%');
        }
        if ($request->filled('title')) {
            $query->where(DB::raw('LOWER(J.SINGKATAN_JABATAN)'), 'like', '%' . strtolower($request->input('title')) . '%');
        }
        if ($request->filled('kpa_code')) {
            $query->where('K.KDKTR', 'like', '%' . $request->input('kpa_code') . '%');
        }
        if ($request->filled('kpa_name')) {
            $query->where('K.NMKTR', 'like', '%' . $request->input('kpa_name') . '%');
        }

        // Add condition for TGL_LISENSI_AKHIR
        $query->where('A.TGL_LISENSI_AKHIR', '>=', DB::raw('SYSDATE'));

        // Sort and get results
        $query->orderBy('A.NO_AGEN', 'asc');

        $results = $query->get();
        return DataTables::of($results)->make(true); // Get the final results

        // Uncomment the line below to return results in JSON format if needed
        // return response()->json($results);
    }
}

