<?php

namespace App\Controller\Admin;

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

class CampaignsController extends AppAdminController
{

    public function index()
    {
        $query = $this->Campaigns->find()
            ->contain([ 'Users', 'CampaignItems']);
        $campaigns = $this->paginate($query);

        $this->set('campaigns', $campaigns);
    }

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

        $campaign = $this->Campaigns->findById($id)
            ->contain(['CampaignItems'])
            ->first();

        if (!$campaign) {
            throw new NotFoundException(__('Campaign Not Found'));
        }

        $this->set('campaign', $campaign);
    }

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

        $campaign = $this->Campaigns->find()
            ->where(['Campaigns.id' => $id])
            ->contain(['CampaignItems'])
            ->first();

        if (!$campaign) {
            throw new NotFoundException(__('Invalid campaign'));
        }

        if ($this->request->is(['post', 'put'])) {
            $this->request->data['price'] = 0;

            foreach ($this->request->data['campaign_items'] as $key => $value) {
                $this->request->data['price'] += $value['purchase'] * $value['advertiser_price'];
            }

            $this->Campaigns->patchEntity($campaign, $this->request->data);
            if ($this->Campaigns->save($campaign)) {
                $this->Flash->success(__('Campaign has been updated.'));
                return $this->redirect(['action' => 'edit', $id]);
            } else {
                $this->Flash->error(__('Unable to update campaign.'));
            }
        }

        $this->set('campaign', $campaign);
    }

    public function pause($id)
    {

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

        $campaign = $this->Campaigns->findById($id)
            ->where(['status' => 'Active'])
            ->first();

        if (!$campaign) {
            $this->Flash->success(__('Campaign not found'));
            return $this->redirect(['action' => 'index']);
        }

        $campaign->status = 'Paused';
        $this->Campaigns->save($campaign);

        return $this->redirect(['action' => 'index']);
    }

    public function resume($id)
    {

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

        $campaign = $this->Campaigns->findById($id)
            ->where(['status' => 'Paused'])
            ->first();

        if (!$campaign) {
            $this->Flash->success(__('Campaign not found'));
            return $this->redirect(['action' => 'index']);
        }

        $campaign->status = 'Active';
        $this->Campaigns->save($campaign);

        return $this->redirect(['action' => 'index']);
    }
}
