<?php

namespace App\Controller\Member;

use App\Controller\Member\AppMemberController;

class WithdrawsController extends AppMemberController
{

    public function index()
    {
        $query = $this->Withdraws->find()
            ->where(['user_id' => $this->Auth->user('id')]);
        $withdraws = $this->paginate($query);

        $this->set('withdraws', $withdraws);

        $tolal_withdrawn = $this->Withdraws->find()
            ->where(['user_id' => $this->Auth->user('id')])
            ->where(['status' => 'Complete'])
            ->sumOf('amount');

        $this->set('tolal_withdrawn', $tolal_withdrawn);

        $pending_withdrawn = $this->Withdraws->find()
            ->where(['user_id' => $this->Auth->user('id')])
            ->where(['status' => 'Pending'])
            ->sumOf('amount');

        $this->set('pending_withdrawn', $pending_withdrawn);

        $user = $this->Withdraws->Users->get($this->Auth->user('id'));
        $this->set('user', $user);
    }

    public function request()
    {

        $this->request->allowMethod(['post', 'put']);

        $user = $this->Withdraws->Users->get($this->Auth->user('id'));

        $withdraw = $this->Withdraws->newEntity();
        $data = [];

        $withdraw->user_id = $this->Auth->user('id');
        $withdraw->status = 'Pending';
        $data['amount'] = (float) $user->publisher_balance;

        if ($data['amount'] < 5) {
            $this->Flash->error(__('Withdraw amount should be greater or equal to $5.00.'));
            return $this->redirect(['action' => 'index']);
        }

        if ($this->Withdraws->save($this->Withdraws->patchEntity($withdraw, $data))) {
            // Rest publisher balance
            $user->publisher_balance = 0;
            $this->Withdraws->Users->save($user);

            $this->Flash->success(__('Your withdraw has been request and under review.'));
        } else {
            $this->Flash->error(__('Unable to request the withdraw.'));
        }
        return $this->redirect(['action' => 'index']);
    }
}
