<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Traits\HasFilterRequest;
use App\Traits\HasSearchRequest;
use Illuminate\Http\Request;

class HistoryPaymentController extends Controller
{
    use HasSearchRequest;
    use HasFilterRequest;

    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index()
    {
        return view('client.pages.user.history_payment');
    }

    public function get(Request $request)
    {
        $search = $request->get('search') ? $request->get('search')['value'] : '';
        $orders = Order::getOrdersWithDiscountAndPackage()
            ->where('orders.user_id', auth()->user()->id)->orderBy('orders.updated_at','desc');

        $this->filterRequest(
            builder: $orders,
            request: $request,
            filterKeys: [
                'from_date' => [
                    'type' => self::F_THAN_EQ_DATETIME,
                    'column' => 'orders.updated_at'
                ],
                'to_date' => [
                    'type' => self::F_LESS_EQ_DATETIME,
                    'column' => 'orders.updated_at'
                ],
            ]
        );

        $this->searchRequest(
            builder: $orders,
            value: $search,
            fields: [
                'orders.payment_id',
                'orders.discount',
                'orders.status',
                'orders.total_price',
                'orders.point',
            ]
        );
        $perPage = $request->input('length');
        $page = ((int) $request->input('start') / (int) $request->input('length')) + 1;
        $history = $orders->paginate(
            perPage: $perPage,
            page: $page
        );

        $data = [
            "recordsTotal" => $history->total(),
            "recordsFiltered" => $history->total(),
            "payload" => $request->all(),
            "data" => $history->getCollection()->map(function ($record) {
                return [
                    '',
                    $record->payment_id,
                    $record->point,
                    $record->package_name,
                    $record->package_price,
                    $record->discount,
                    $record->discounted_package_price,
                    $record->total_price,
                    $record->updated_at,
                    $record->status
                ];
            })->toArray()
        ];

        return response()->json($data);
    }
}
