<?php

  // Build on top of admin controller
  AngieApplication::useController('admin', ENVIRONMENT_FRAMEWORK_INJECT_INTO);

  /**
   * Identity administration controller
   * 
   * @package activeCollab.modules.system
   * @subpackage controller
   */
  class IdentityAdminController extends AdminController {
  
    /**
     * Show identity admin settings
     */
    function index() {
      if (!$this->request->isAsyncCall()) {
        $this->response->badRequest();
      } // if
      
      $settings_data = $this->request->post('settings', ConfigOptions::getValue(array(
        'identity_name',
      )));

      $timestamp = '?timestamp=' . time();
        
      $this->response->assign(array(
        'settings_data' => $settings_data,
        'small_logo_url' => AngieApplication::getBrandImageUrl('logo.16x16.png') . $timestamp,
        'medium_logo_url' => AngieApplication::getBrandImageUrl('logo.40x40.png') . $timestamp,
        'large_logo_url' => AngieApplication::getBrandImageUrl('logo.80x80.png') . $timestamp,
        'larger_logo_url' => AngieApplication::getBrandImageUrl('logo.128x128.png') . $timestamp,
        'photo_logo_url' => AngieApplication::getBrandImageUrl('logo.256x256.png') . $timestamp,
      ));

      if($this->request->isSubmitted()) {

        try {
          if (isset($settings_data['identity_name']) && $settings_data['identity_name']) {
            ConfigOptions::setValue('identity_name', $settings_data['identity_name']);
          } else {
            ConfigOptions::setValue('identity_name', null);
          } // if

          // logo is uploaded
          $logo = array_var($_FILES, 'logo');
          if (is_array($logo)) {
            $uploaded_file_path = array_var($logo, 'tmp_name', null);
            $uploaded_file_name = array_var($logo, 'name', null);
            $revert_files = array();

            if (!$uploaded_file_path) {
              throw new Exception(lang('Image upload failed. Check PHP configuration'));
            } // if

            $temporary_file = move_uploaded_file_to_temp_directory($uploaded_file_path, $uploaded_file_name);
            if (!$temporary_file) {
              throw new Exception(lang('Could not move uploaded image to temporary folder'));
            } else {
              $revert_files[] = $temporary_file;
            } // if

            // check if branding folder is writable
            $branding_path = PUBLIC_PATH . '/brand';
            if (!folder_is_writable($branding_path)) {
              throw new Exception(lang('Branding folder is not writable'));
            } // if

            // open source image
            $image_resource = open_image($temporary_file);
            if (!$image_resource) {
              throw new Exception(lang('Could not read uploaded image'));
            } // if

            // check if all images are writable and create resized versions
            $sizes = array('256', '128', '80', '40', '16');
            $destination = array();
            foreach ($sizes as $size) {
              $destination[$size] = $branding_path . "/logo.{$size}x{$size}.png";
              if (!file_is_writable($destination[$size], false)) {
                throw new Exception(lang('Branding file :file is not writable', array('file' => $destination[$size])));
              } // if

              $resize_result = scale_and_fit_image($image_resource, $destination[$size] . '.temp', $size, $size, IMAGETYPE_PNG);
              if (!$resize_result) {
                throw new Exception(lang('Could not resize uploaded image to dimensions :size x :size', array('size' => $size)));
              } else {
                $revert_files[] = $destination[$size] . '.temp';
              } // if
            } // foreach

            // remove old images, and set new ones
            foreach ($sizes as $size) {
              $destination[$size] = $branding_path . "/logo.{$size}x{$size}.png";
              @unlink($destination[$size]);
              rename($destination[$size] . '.temp', $destination[$size]);
            } // foreach
          } // if

          $this->wireframe->javascriptAssign('identity_name', ConfigOptions::getValue('identity_name'));

          $this->response->ok();
        } catch (Exception $e) {
          // remove all temporary files
          if (is_foreachable($revert_files)) {
            foreach ($revert_files as $revert_file) {
              @unlink($revert_file);
            } // foreach
          } // if

          if ($logo) {
            die(JSON::encode(array(
              'ajax_error' => true,
              'ajax_message' => $e->getMessage()
            )));
          } else {
            $this->response->exception($e);
          } // if
        } // try

      } // if

    } // index
    
  }