<?php

namespace App\Http\Controllers\Vendor;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Lib\FormProcessor;
use App\Lib\GoogleAuthenticator;
use App\Models\Deposit;
use App\Models\DeviceToken;
use App\Models\Form;
use App\Models\Installment;
use App\Models\Invest;
use App\Models\Profit;
use App\Models\Property;
use App\Models\Referral;
use App\Models\SupportTicket;
use App\Models\Transaction;
use App\Models\Withdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class VendorController extends Controller {
    public function home() {
        $pageTitle = 'Dashboard';
        $vendor    = auth()->guard('vendor')->user();

        $widget['balance']          = $vendor->balance;
        $widget['total_deposit']    = Deposit::where('user_id', $vendor->id)->where('status', Status::PAYMENT_SUCCESS)->sum('amount');
        $widget['total_withdraw']   = Withdrawal::where('user_id', $vendor->id)->where('status', Status::PAYMENT_SUCCESS)->sum('amount');
        $widget['total_ticket']     = SupportTicket::where('user_id', $vendor->id)->count();
        $widget['total_investment'] = Invest::myProperty()->sum('paid_amount');
        $widget['total_profit']     = Invest::myProperty()->where('invest_status', Status::COMPLETED)->sum('total_profit');
        $widget['total_property']   = Property::invested()->where('vendor_id', auth()->guard('vendor')->id())->count();
        $nextProfitSchedule         = Invest::where('user_id', $vendor->id)->with('property')->where('profit_status', Status::RUNNING)->orderBy('next_profit_date')->first();

        $nextInstallment = Installment::whereHas('invest', function ($invest) use ($vendor) {
            $invest->where('user_id', $vendor->id);
        })->where('status', Status::INSTALLMENT_PENDING)->orderBy('next_time')->with(['invest'])->first();

        $trxReport['date'] = collect([]);
        $investTrx         = Transaction::where('user_id', $vendor->id)
            ->where(function ($query) {
                $query->where('remark', 'down_payment')->orWhere('remark', 'installment');
            })
            ->where('created_at', '>=', Carbon::now()->subDays(30))
            ->selectRaw("SUM(amount) as amount, DATE_FORMAT(created_at,'%Y-%m-%d') as date")
            ->orderBy('created_at')
            ->groupBy('date')
            ->get();

        $investTrx->map(function ($trxData) use ($trxReport) {
            $trxReport['date']->push($trxData->date);
        });

        $profitTrx = Transaction::where('user_id', $vendor->id)->where('remark', 'profit')
            ->where('created_at', '>=', Carbon::now()->subDays(30))
            ->selectRaw("SUM(amount) as amount, DATE_FORMAT(created_at,'%Y-%m-%d') as date")
            ->orderBy('created_at')
            ->groupBy('date')
            ->get();
        $profitTrx->map(function ($trxData) use ($trxReport) {
            $trxReport['date']->push($trxData->date);
        });
        $trxReport['date'] = dateSorting($trxReport['date']->unique()->toArray());

        $nextInvestProfits = Invest::myProperty()->where('profit_status', Status::RUNNING)->whereDate('next_profit_date', '<=', now()->addDays(7))->orderBy('next_profit_date')->take(10)->get();
        return view('vendor.dashboard', compact('pageTitle', 'widget', 'nextInstallment', 'investTrx', 'profitTrx', 'trxReport', 'vendor', 'nextProfitSchedule', 'nextInvestProfits'));
    }

    public function depositHistory(Request $request) {
        $pageTitle = 'Deposit History';
        $deposits  = auth()->guard('vendor')->user()->deposits()->searchable(['trx'])->with(['gateway'])->orderBy('id', 'desc')->paginate(getPaginate());
        return view('vendor.deposit_history', compact('pageTitle', 'deposits'));
    }

    public function show2faForm() {
        $ga        = new GoogleAuthenticator();
        $vendor    = auth()->guard('vendor')->user();
        $secret    = $ga->createSecret();
        $qrCodeUrl = $ga->getQRCodeGoogleUrl($vendor->username . '@' . gs('site_name'), $secret);
        $pageTitle = '2FA Security';
        return view('vendor.twofactor', compact('pageTitle', 'secret', 'qrCodeUrl', 'vendor'));
    }

    public function create2fa(Request $request) {
        $vendor = auth()->guard('vendor')->user();
        $request->validate([
            'key'  => 'required',
            'code' => 'required',
        ]);
        $response = verifyG2fa($vendor, $request->code, $request->key);
        if ($response) {
            $vendor->tsc = $request->key;
            $vendor->ts  = Status::ENABLE;
            $vendor->save();
            $notify[] = ['success', 'Two factor authenticator activated successfully'];
            return back()->withNotify($notify);
        } else {
            $notify[] = ['error', 'Wrong verification code'];
            return back()->withNotify($notify);
        }
    }

    public function disable2fa(Request $request) {
        $request->validate([
            'code' => 'required',
        ]);

        $vendor   = auth()->guard('vendor')->user();
        $response = verifyG2fa($vendor, $request->code);
        if ($response) {
            $vendor->tsc = null;
            $vendor->ts  = Status::DISABLE;
            $vendor->save();
            $notify[] = ['success', 'Two factor authenticator deactivated successfully'];
        } else {
            $notify[] = ['error', 'Wrong verification code'];
        }
        return back()->withNotify($notify);
    }

    public function transactions() {
        $pageTitle = 'Transactions';
        $remarks   = Transaction::distinct('remark')->orderBy('remark')->get('remark');

        $transactions = Transaction::where('vendor_id', auth()->guard('vendor')->id())->searchable(['trx'])->filter(['trx_type', 'remark'])->orderBy('id', 'desc')->paginate(getPaginate());

        return view('vendor.transactions', compact('pageTitle', 'transactions', 'remarks'));
    }

    public function kybForm() {
        if (auth()->guard('vendor')->user()->kv == Status::KYB_PENDING) {
            $notify[] = ['error', 'Your KYB is under review'];
            return to_route('vendor.home')->withNotify($notify);
        }
        if (auth()->guard('vendor')->user()->kv == Status::KYB_VERIFIED) {
            $notify[] = ['error', 'You are already KYB verified'];
            return to_route('vendor.home')->withNotify($notify);
        }
        $pageTitle = 'KYB Form';
        $form      = Form::where('act', 'kyb')->first();
        return view('vendor.kyb.form', compact('pageTitle', 'form'));
    }

    public function kybData() {
        $vendor    = auth()->guard('vendor')->user();
        $pageTitle = 'KYB Data';
        abort_if($vendor->kv == Status::VERIFIED, 403);
        return view('vendor.kyB.info', compact('pageTitle', 'vendor'));
    }

    public function kybSubmit(Request $request) {
        $form           = Form::where('act', 'kyb')->firstOrFail();
        $formData       = $form->form_data;
        $formProcessor  = new FormProcessor();
        $validationRule = $formProcessor->valueValidation($formData);
        $request->validate($validationRule);
        $vendor = auth()->guard('vendor')->user();
        foreach (@$vendor->kyc_data ?? [] as $kycData) {
            if ($kycData->type == 'file') {
                fileManager()->removeFile(getFilePath('verify') . '/' . $kycData->value);
            }
        }
        $vendorData                   = $formProcessor->processFormData($request, $formData);
        $vendor->kyc_data             = $vendorData;
        $vendor->kyc_rejection_reason = null;
        $vendor->kv                   = Status::KYC_PENDING;
        $vendor->save();

        $notify[] = ['success', 'KYB data submitted successfully'];
        return to_route('vendor.home')->withNotify($notify);
    }

    public function vendorData() {
        $vendor = auth()->guard('vendor')->user();

        if ($vendor->profile_complete == Status::YES) {
            return to_route('vendor.home');
        }

        $pageTitle  = 'Vendor Data';
        $info       = json_decode(json_encode(getIpInfo()), true);
        $mobileCode = @implode(',', $info['code']);
        $countries  = json_decode(file_get_contents(resource_path('views/partials/country.json')));

        return view('vendor.vendor_data', compact('pageTitle', 'vendor', 'countries', 'mobileCode'));
    }

    public function vendorDataSubmit(Request $request) {
        $vendor = auth()->guard('vendor')->user();

        if ($vendor->profile_complete == Status::YES) {
            return to_route('vendor.home');
        }

        $countryData  = (array) json_decode(file_get_contents(resource_path('views/partials/country.json')));
        $countryCodes = implode(',', array_keys($countryData));
        $mobileCodes  = implode(',', array_column($countryData, 'dial_code'));
        $countries    = implode(',', array_column($countryData, 'country'));

        $request->validate([
            'country_code' => 'required|in:' . $countryCodes,
            'country'      => 'required|in:' . $countries,
            'mobile_code'  => 'required|in:' . $mobileCodes,
            'username'     => 'required|unique:users|min:6',
            'mobile'       => ['required', 'regex:/^([0-9]*)$/', Rule::unique('users')->where('dial_code', $request->mobile_code)],
            'company_name' => 'required|string|unique:vendors,company_name',
        ]);

        if (preg_match("/[^a-z0-9_]/", trim($request->username))) {
            $notify[] = ['info', 'Username can contain only small letters, numbers and underscore.'];
            $notify[] = ['error', 'No special character, space or capital letters in username.'];
            return back()->withNotify($notify)->withInput($request->all());
        }

        $vendor->country_code     = $request->country_code;
        $vendor->mobile           = $request->mobile;
        $vendor->username         = $request->username;
        $vendor->address          = $request->address;
        $vendor->city             = $request->city;
        $vendor->state            = $request->state;
        $vendor->zip              = $request->zip;
        $vendor->country_name     = @$request->country;
        $vendor->dial_code        = $request->mobile_code;
        $vendor->company_name     = $request->company_name;
        $vendor->profile_complete = Status::YES;
        $vendor->save();

        return to_route('vendor.home');
    }

    public function addDeviceToken(Request $request) {

        $validator = Validator::make($request->all(), [
            'token' => 'required',
        ]);

        if ($validator->fails()) {
            return ['success' => false, 'errors' => $validator->errors()->all()];
        }

        $deviceToken = DeviceToken::where('token', $request->token)->first();

        if ($deviceToken) {
            return ['success' => true, 'message' => 'Already exists'];
        }

        $deviceToken            = new DeviceToken();
        $deviceToken->vendor_id = auth()->guard('vendor')->user()->id;
        $deviceToken->token     = $request->token;
        $deviceToken->is_app    = Status::NO;
        $deviceToken->save();

        return ['success' => true, 'message' => 'Token saved successfully'];
    }

    public function downloadAttachment($fileHash) {
        $filePath  = decrypt($fileHash);
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        $title     = slug(gs('site_name')) . '- attachments.' . $extension;
        try {
            $mimetype = mime_content_type($filePath);
        } catch (\Exception $e) {
            $notify[] = ['error', 'File does not exists'];
            return back()->withNotify($notify);
        }
        header('Content-Disposition: attachment; filename="' . $title);
        header("Content-Type: " . $mimetype);
        return readfile($filePath);
    }

    public function profitHistory() {
        $pageTitle = 'Profit History';
        $profits   = Profit::where('user_id', auth()->id())
            ->success()
            ->searchable(['transaction:trx', 'invest:investment_id', 'property:title'])
            ->with(['user', 'property', 'invest', 'transaction'])
            ->orderByDesc('updated_at')
            ->paginate(getPaginate());

        return view('vendor.profit', compact('pageTitle', 'profits'));
    }

    public function referrals() {
        $pageTitle = 'Referrals';
        $user      = auth()->guard('vendor')->user();
        $maxLevel  = Referral::max('level');
        return view('vendor.referrals', compact('pageTitle', 'user', 'maxLevel'));
    }
}
