<?php

namespace App\Controller\Admin;

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

class OptionsController extends AppAdminController
{

    public function index()
    {
        $options = $this->Options->find()->all();

        $settings = [];
        foreach ($options as $option) {
            $settings[$option->name] = [
                'id' => $option->id,
                'value' => $option->value
            ];
        }

        if ($this->request->is(['post', 'put'])) {
            foreach ($this->request->data['Options'] as $key => $optionData) {
                $option = $this->Options->newEntity();
                $option->id = $key;
                $option = $this->Options->patchEntity($option, $optionData);
                $this->Options->save($option);
            }
            \Cake\Cache\Cache::delete('options');
            $this->Flash->success('Settings have been saved.');
            return $this->redirect(['action' => 'index']);
        }

        $this->set('options', $options);
        $this->set('settings', $settings);
    }

    public function pricing()
    {
        $option = $this->Options->findByName('interstitial_price')->first();
        if (!$option) {
            throw new NotFoundException(__('Invalid option'));
        }

        $option->value = unserialize($option->value);

        if ($this->request->is(['post', 'put'])) {
            foreach ($this->request->data['value'] as $key => $value) {
                if (!empty($value['advertiser']) && !empty($value['publisher'])) {
                    $this->request->data['value'][$key] = [
                        'advertiser' => abs($value['advertiser']),
                        'publisher' => abs($value['publisher'])
                    ];
                } else {
                    $this->request->data['value'][$key] = [
                        'advertiser' => '',
                        'publisher' => ''
                    ];
                }
            }

            //debug( $valuse );

            $this->request->data['value'] = serialize($this->request->data['value']);

            $this->Options->patchEntity($option, $this->request->data);
            if ($this->Options->save($option)) {
                //debug($option);
                $this->Flash->success('Prices have been updated.');
                \Cake\Cache\Cache::delete('options');
                return $this->redirect(['action' => 'pricing']);
            } else {
                $this->Session->setFlash('Oops! There are mistakes in the form. Please make the correction.');
            }
        }

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