<?php

namespace App\Controller;

use App\Controller\FrontController;
use Cake\Event\Event;
use Cake\Network\Exception\NotFoundException;
use Cake\Network\Exception\BadRequestException;

class BundlesController extends FrontController
{
    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->viewBuilder()->layout('front');
        $this->Auth->allow(['view']);
    }

    public function view($username = null, $id = null)
    {
        if (!$username || !$id) {
            throw new NotFoundException(__('404 Not Found'));
        }

        $user = $this->Bundles->Users->find()
            ->contain(['Plans'])
            ->where([
                'username' => $username,
                'status' => 1
            ])
            ->first();

        if (!$user) {
            throw new NotFoundException(__('404 Not Found'));
        }
        $this->set('user', $user);

        $user_plan = get_user_plan($user);

        $plan_disable_ads_area1 = $user_plan->disable_ads_area1;
        $plan_disable_ads_area2 = $user_plan->disable_ads_area2;

        $ads_area1 = get_option('ads_area1', '');
        if ($plan_disable_ads_area1) {
            $ads_area1 = '';
        }
        $this->set('ads_area1', $ads_area1);

        $ads_area2 = get_option('ads_area2', '');
        if ($plan_disable_ads_area2) {
            $ads_area2 = '';
        }
        $this->set('ads_area2', $ads_area2);

        $bundle = $this->Bundles->find()
            ->where([
                'user_id' => $user->id,
                'user_bundle_id' => $id,
                'private' => 0
            ])
            ->first();

        if (!$bundle) {
            throw new NotFoundException(__('404 Not Found'));
        }
        $this->set('bundle', $bundle);

        $bundle->views += 1;
        $bundle->modified = $bundle->modified;
        $this->Bundles->save($bundle);

        $links = $this->Bundles->Links->find()
            ->where([
                'bundle_id' => $bundle->id,
                'status <>' => 3
            ]);
        $this->set('links', $links);
    }
}
