<?php

namespace App\Http\Controllers;

use App\Helpers\Helper;
use App\Models\Payment;
use App\Models\Pricing;
use App\Services\PaymentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BuySMSController extends Controller
{
    use Helper;

    public function __construct()
    {
        $this->model = new Payment();
    }

    public function index()
    {
        $keyword = input('name');
        $end_date = input('end_date');
        $start_date = input('start_date');

        $user = auth()->user();
        $data = $this->model->with(['users', 'package', 'userPackage', 'expired:payment_id,expired_date'])
            ->orderBy('id', 'desc')
            ->where('user_id', $user->id)
            ->when($keyword, function ($query) use ($keyword) {
                $query->whereHas('users', function ($query) use ($keyword) {
                    $query->where('name', 'LIKE', "%$keyword%");
                });
            })
            ->when(($start_date || $end_date), function ($query) use ($start_date, $end_date) {
                if ($start_date) {
                    $query->where('created_at', '>=', $start_date);
                }
                if ($end_date) {
                    $query->where('created_at', '<=', $end_date);
                }
            })
            ->paginate(request()->input('perPage', $this->perPage));

        return returnData(2000, $data);
    }

    public function store(Request $request)
    {
        try {
            $validate = $this->model->validate($request->all());

            if ($validate->fails()) {
                return returnData(3000, $validate->errors(), 'Validation Failed');
            }

            $userId = auth()->user()->id;
            $paymentType = (int) ($request->payement_type ?? Payment::TYPE_REGULAR);

            // Due check
            $duePayments = Payment::where('user_id', $userId)
                ->where('payement_type', Payment::TYPE_DUE_ADVANCED)
                ->where('due_amount', '>', 0)
                ->sum('due_amount');

            if ($duePayments > 0 && $paymentType === Payment::TYPE_DUE_ADVANCED) {
                return returnData(3000, null, 'You have a due amount of ' . $duePayments . '. Please clear your due first.');
            }

            $payment = PaymentService::createManualPayment($request->all(), $userId);

            return returnData(2000, $payment, 'Payment Request Successfully Submitted, Waiting For Admin Approval');
        } catch (\Exception $exception) {
            return returnData(5000, $exception->getMessage(), $exception->getMessage());
        }
    }
}
