<?php

namespace App\Http\Controllers\Member;

use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use App\Http\Controllers\Controller;
use App\Models\Invoice;

class MemberInvoiceController extends Controller
{
    public function index(Request $request)
    {
        $user_id = auth()->user()->id;
        if ($request->ajax()) {
            $date1 = $request->date1;
            $date2 = $request->date2;
            $status = $request->status;

            $data = Invoice::where('invoices.user_id', '=', $user_id)
                ->leftJoin('vps_details', 'vps_details.id', '=', 'invoices.vps_details_id')
                ->leftJoin('vps_proxies', 'vps_proxies.id', '=', 'vps_details.vps_proxies_id')
                ->leftJoin('vps', 'vps.id', '=', 'vps_details.vps_id')
                ->leftJoin('users', 'users.id', '=', 'invoices.user_id')
                ->select('invoices.*', 'vps.name AS vps_name', 'users.email AS email');
            if ($date1 && $date2) {
                $start = $date1 . ' 00:00:00';
                $end = $date2 . ' 23:59:59';
                $data->whereBetween('invoices.created_at', [$start, $end]);
            }

            if ($status && $status !== 'ALL') {
                if ($status === 'TOPUP') {
                    $data->whereNull('invoices.vps_details_id');
                } elseif ($status === 'SUBSCRIPTION') {
                    $data->whereNotNull('invoices.vps_details_id');
                }
            }

            return Datatables::of($data)
                ->editColumn('created_at', fn($row) => $row->created_at->format('d-m-Y H:i:s'))
                ->editColumn('vps_name', fn($row) => $row->vps_name ?? 'TOPUP')
                ->addIndexColumn()
                ->make(true);
        }

        return view('admin.invoice');
    }
}
