<?php

namespace App\Controller\Member;

use App\Controller\Member\AppMemberController;
use Cake\Mailer\MailerAwareTrait;
use Cake\I18n\Time;

class UsersController extends AppMemberController
{

    use MailerAwareTrait;

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

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

        $total_views = $this->Users->Statistics->find()
            ->where(['Statistics.user_id' => $this->Auth->user('id')])
            ->where(['Statistics.owner_earn >' => 0])
            ->count();

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

        $total_earnings = $this->Users->Statistics->find()
            ->where(['user_id' => $this->Auth->user('id')])
            ->where(['publisher_earn >' => 0])
            ->sumOf('publisher_earn');

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

///////////////////////////

        $last_record = $this->Users->Statistics->find()
            ->select([ 'created',
                'year' => 'YEAR(created)',
                'month' => 'MONTH(created)'
            ])
            ->where(['user_id' => $this->Auth->user('id')])
            ->order(['created' => 'DESC'])
            ->first();
        
        if (!$last_record) {
            $last_record = new \stdClass();
            $last_record->created = $last_record->created = Time::now()->format('Y-m-d H:i:s');
        }

        $first_first = $this->Users->Statistics->find()
            ->select([ 'created',
                'year' => 'YEAR(created)',
                'month' => 'MONTH(created)'
            ])
            ->where(['user_id' => $this->Auth->user('id')])
            ->order(['created' => 'ASC'])
            ->first();
        
        if (!$first_first) {
            $first_first = new \stdClass();
            $first_first->created = Time::now()->modify('-1 week')->format('Y-m-d H:i:s');
        }

        $year_month = [];

        $last_month = new Time($last_record->created);
        //$last_month = strtotime($last_record->created);
        $first_month = new Time($first_first->created);
        //$first_month = strtotime($first_first->created);

        while ($first_month <= $last_month) {
            $year_month[$last_month->format('Y-m')] = $last_month->format('F Y');

            $last_month->modify('-1 month');
        }

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

        $to_month = Time::now()->format('Y-m');
        if ($this->request->is('post')) {
            $to_month = explode('-', $this->request->data['to_month']);
            $year = $to_month[0];
            $month = $to_month[1];
        } else {
            $time = new Time($to_month);
            $current_time = $time->startOfMonth();

            $year = $current_time->format('Y');
            $month = $current_time->format('m');
        }

        $links = $this->Users->Links->find()
            ->select([
                'day' => 'DATE_FORMAT(Links.created,"%d-%m-%Y")',
                'count' => 'COUNT(Links.created)'])
            ->where(['Links.user_id' => $this->Auth->user('id')])
            //->where( ['Links.created >=' => $to_month_form ] )
            ->where(["YEAR(Links.created) = :year AND MONTH(Links.created) = :month"])
            ->order(['Links.created' => 'DESC'])
            ->bind(':year', $year, 'integer')
            ->bind(':month', $month, 'integer')
            ->group('day');

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

        $views = $this->Users->Statistics->find()
            ->select([
                'day' => 'DATE_FORMAT(Statistics.created,"%d-%m-%Y")',
                'count' => 'COUNT(Statistics.created)',
                'earnings' => 'SUM(Statistics.publisher_earn)',
            ])
            ->where(['Statistics.user_id' => $this->Auth->user('id')])
            //->where( ['Statistics.created >=' => $to_month_form ] )
            ->where(["YEAR(Statistics.created) = :year AND MONTH(Statistics.created) = :month"])
            ->where(['Statistics.owner_earn >' => 0])
            ->order(['Statistics.created' => 'DESC'])
            ->bind(':year', $year, 'integer')
            ->bind(':month', $month, 'integer')
            ->group('day');

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

        $CurrentMonthDays = [];
        
        $targetTime = Time::now();
        $targetTime->year($year)
            ->month($month)
            ->day(1);

        for ($i = 1; $i <= $targetTime->format('t'); $i++) {
            $CurrentMonthDays[$i . "-" . $month . "-" . $year] = [
                'view' => 0,
                'earn' => 0,
            ];
        }
        foreach ($views as $view) {
            $day = Time::now()->modify($view->day)->format('j-m-Y');
            $CurrentMonthDays[$day]['view'] = $view->count;
            $CurrentMonthDays[$day]['earn'] = $view->earnings;
        }
        $this->set('CurrentMonthDays', $CurrentMonthDays);
    }

    public function profile()
    {
        $user = $this->Users->findById($this->Auth->user('id'))->first();

        if ($this->request->is([ 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->data);
            //debug($user->errors());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('Profile has been updated'));
                $this->redirect([ 'action' => 'profile']);
            } else {
                $this->Flash->error(__('Oops! There are mistakes in the form. Please make the correction.'));
            }
        }
        unset($user->password);
        $this->set('user', $user);
    }

    public function changeEmail($username = null, $key = null)
    {
        if (!$username && !$key) {
            $user = $this->Users->findById($this->Auth->user('id'))->first();

            if ($this->request->is([ 'post', 'put'])) {
                $uuid = \Cake\Utility\Text::uuid();

                $user->activation_key = \Cake\Utility\Security::hash($uuid, 'sha1', true);

                $user = $this->Users->patchEntity($user, $this->request->data, ['validate' => 'changEemail']);

                if ($this->Users->save($user)) {
                    // Send rest email
                    $this->getMailer('User')->send('changeEmail', [$user]);

                    $this->Flash->success(__('Kindly check your email to confirm it.'));

                    $this->redirect([ 'action' => 'changeEmail']);
                } else {
                    $this->Flash->error(__('Oops! There are mistakes in the form. Please make the correction.'));
                }
            }
            $this->set('user', $user);
        } else {
            $user = $this->Users->find('all')
                ->where([
                    'active' => 1,
                    'username' => $username,
                    'activation_key' => $key
                ])
                ->first();

            if (!$user) {
                $this->Flash->error(__('Invalid Activation.'));
                return $this->redirect([ 'action' => 'changeEmail']);
            }

            $user->email = $user->temp_email;
            $user->temp_email = '';
            $user->activation_key = '';

            if ($this->Users->save($user)) {
                $this->Flash->success(__('Your email has been confirmed.'));

                $this->Auth->logout();

                return $this->redirect([ 'action' => 'signin']);
            } else {
                $this->Flash->error(__('Unable to confirm your email.'));
                return $this->redirect([ 'action' => 'changeEmail']);
            }
        }
    }

    public function changePassword()
    {
        $user = $this->Users->findById($this->Auth->user('id'))->first();

        if ($this->request->is([ 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->data, ['validate' => 'changePassword']);
            //debug($user->errors());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('Password has been updated'));
                $this->redirect([ 'action' => 'changePassword']);
            } else {
                $this->Flash->error(__('Oops! There are mistakes in the form. Please make the correction.'));
            }
        }
        unset($user->password);
        $this->set('user', $user);
    }
}
