<?php

namespace App\Controller\Admin;

use App\Controller\Admin\AppAdminController;
use Cake\Network\Exception\NotFoundException;
use Cake\I18n\Time;

class UsersController extends AppAdminController
{

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

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

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

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

        $publisher_earnings = $this->Users->Statistics->find()
            ->where(['publisher_earn >' => 0])
            ->sumOf('publisher_earn');

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

        $owner_earnings = $this->Users->Statistics->find()
            ->where(['owner_earn >' => 0])
            ->sumOf('owner_earn');

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

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

        $last_record = $this->Users->Statistics->find()
            ->select([ 'created',
                'year' => 'YEAR(created)',
                'month' => 'MONTH(created)'
            ])
            ->order(['created' => 'DESC'])
            ->first();

        if (!$last_record) {
            $last_record = new \stdClass();
            $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)'
            ])
            ->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.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.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 index()
    {
        $query = $this->Users->find();
        $users = $this->paginate($query);
        $this->set('users', $users);
    }

    public function view($id = null)
    {
        if (!$id) {
            throw new NotFoundException(__('Invalid User'));
        }

        $user = $this->Users->findById($id)->first();
        if (!$user) {
            throw new NotFoundException(__('Invalid User'));
        }
        $this->set('user', $user);
    }
    
    public function add()
    {
        $user = $this->Users->newEntity();

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data);

            $user->role = 'member';
            $user->status = 'active';

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

            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been added.'));
                return $this->redirect(['action' => 'view', $user->id]);
            }
            $this->Flash->error(__('Unable to add the user.'));
        }
        $this->set('user', $user);
    }
    
    public function edit($id = null)
    {
        if (!$id) {
            throw new NotFoundException(__('Invalid User'));
        }
        
        $user = $this->Users->get($id);
        if (!$user) {
            throw new NotFoundException(__('Invalid User'));
        }

        if ($this->request->is(['post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->data);

            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been updated.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('Unable to edit user.'));
        }
        $this->set('user', $user);
    }
    
    public function deactivate($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);

        $user = $this->Users->findById($id)->first();
        
        $user->status = 'inactive';

        if ($this->Users->save($user)) {
            $this->Flash->success(__('The Link with id: {0} has been deactivated.', $user->id));
            return $this->redirect(['action' => 'index']);
        }
    }
}
