<?php

/**
 * Implements hook_menu().
 */
function mkbh_projekter_page_menu()
{
    return [
        'projekter/more/%/%' => [
            'title' => 'Ajax load more for projects',
            'page callback' => 'mkbh_projekter_page_load_more',
            'page arguments' => [2, 3],
            'delivery callback' => 'ajax_deliver',
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        ],
    ];
}

/**
 * Implements hook_block_info().
 */
function mkbh_projekter_page_block_info()
{
    return [
        'mkbh_projekter_page_projekter' => [
            'info' => t('[Projekter] Projekter'),
            'cache' => DRUPAL_NO_CACHE,
        ],
    ];
}

/**
 * Implements hook_block_view().
 */
function mkbh_projekter_page_block_view($delta = '')
{
    $block = [];

    switch ($delta) {
        case 'mkbh_projekter_page_projekter':
            $block['content'] = mkbh_projekter_page_projekter_content();
            break;
    }

    return $block;
}

/**
 * Implements hook_theme().
 */
function mkbh_projekter_page_theme($existing, $type, $theme, $path)
{
    return [
        'mkbh_projekter_page' => [
            'variables' => [
                'form' => NULL,
            ],
            'path' => $path . '/templates',
            'template' => 'mkbh-projekter-page',
        ],
        'mkbh_projekter_page_cards' => [
            'variables' => [
                'items' => NULL,
            ],
            'path' => $path . '/templates',
            'template' => 'mkbh-projekter-page-cards',
        ],
        'mkbh_projekter_page_list' => [
            'variables' => [
                'items' => NULL,
            ],
            'path' => $path . '/templates',
            'template' => 'mkbh-projekter-page-list',
        ],
        'mkbh_projekter_page_map_popup' => [
            'variables' => [
                'title' => NULL,
                'district' => NULL,
            ],
            'path' => $path . '/templates',
            'template' => 'mkbh-projekter-page-map-popup',
        ],
    ];
}

/**
 * Function for returning content for mkbh_projekter_page_projekter block.
 *
 * @return array
 */
function mkbh_projekter_page_projekter_content()
{
    $view_mode = !isset($_GET['view_m']) ? 'cards' : $_GET['view_m'];
    $form = drupal_get_form('mkbh_projekter_page_projekter_form', $view_mode);

    return [
        '#theme' => 'mkbh_projekter_page',
        '#form' => $form,
        '#info' => [
            '#theme' => 'mkbh_projekter_page_map_popup',
            '#title' => '',
            '#district' => '',
        ],
        '#attached' => [
            'js' => [
                drupal_get_path('module', 'mkbh_projekter_page') . '/js/projekter-map.js',
                libraries_get_path('leaflet') . '/leaflet.js',
                libraries_get_path('leaflet') . '/Leaflet.fullscreen.js',
                libraries_get_path('isMobile') . '/isMobile.js',
            ],
            'css' => [
                libraries_get_path('leaflet') . '/leaflet.css',
                libraries_get_path('leaflet') . '/leaflet.fullscreen.css',
            ],
        ],
    ];
}

/**
 * Form with filters and items result.
 */
function mkbh_projekter_page_projekter_form($form, &$form_state, $view_mode)
{
    $types = [];

    $types_voc = taxonomy_vocabulary_machine_name_load('project_type');
    foreach (taxonomy_term_load_multiple([], ['vid' => $types_voc->vid]) as $type) {
        $types[$type->tid] = $type->name;
    }

    $districts = [];

    $districts_voc = taxonomy_vocabulary_machine_name_load('city_districts');
    foreach (taxonomy_term_load_multiple([], ['vid' => $districts_voc->vid]) as $district) {
        $districts[$district->tid] = $district->name;
    }

    $default_values = [
        'sort' => isset($_GET['sort']) ? $_GET['sort'] : 'abc',
        'district' => isset($_GET['city']) ? $_GET['city'] : 'all',
        'type' => isset($_GET['type']) ? $_GET['type'] : 'all',
        'status' => isset($_GET['status']) ? $_GET['status'] : 'all',
    ];

    $sorting_link_next = $default_values['sort'] == 'abc' ? 'year' : 'abc';
    $sorting_link_label = $default_values['sort'] == 'abc' ? t('ÅR') : t('A-Å');
    $sorting_link = l($sorting_link_label, '', [
        'attributes' => [
            'data-switch-to' => $sorting_link_next,
            'data-target' => 'sorting_select',
        ],
    ]);

    $form['filters'] = [
        '#type' => 'container',
        '#attributes' => [
            'class' => ['col col-md-12 filters-block'],
        ],
        [
            '#type' => 'container',
            '#attributes' => [
                'class' => ['col col-md-2 sorting'],
            ],
            [
                'sorting' => [
                    '#type' => 'select',
                    '#title' => t('sort'),
                    '#options' => [
                        'abc' => t('A-Å'),
                        'year' => t('ÅR'),
                    ],
                    '#default_value' => [$default_values['sort']],
                    '#id' => 'sorting_select',
                    '#attributes' => [
                        'style' => 'display: none;',
                    ],
                    '#field_prefix' => '<div class="sorting-trigger">' . $sorting_link . '</div>',
                ],
            ],
        ],
        [
            '#type' => 'container',
            '#attributes' => [
                'class' => ['col col-md-10 filtering'],
            ],
            [
                '#type' => 'container',
                '#attributes' => [
                    'class' => ['col col-md-4'],
                ],
                [
                    'bydel' => [
                        '#type' => 'select',
                        '#title' => t('bydel'),
                        '#options' => $districts,
                        '#empty_option' => t('alle'),
                        '#empty_value' => 'all',
                        '#default_value' => [$default_values['district']],
                    ],
                ],
            ],
            [
                '#type' => 'container',
                '#attributes' => [
                    'class' => ['col col-md-4'],
                ],
                [
                    'type' => [
                        '#type' => 'select',
                        '#title' => t('type'),
                        '#options' => $types,
                        '#empty_option' => t('alle'),
                        '#empty_value' => 'all',
                        '#default_value' => [$default_values['type']],
                    ],
                ],
            ],
            [
                '#type' => 'container',
                '#attributes' => [
                    'class' => ['col col-md-4'],
                ],
                [
                    'status' => [
                        '#type' => 'select',
                        '#title' => t('status'),
                        '#options' => [
                            'afsluttet' => t('Afsluttet'),
                            'under_opforsel' => t('Under opførsel'),
                            'plan' => t('Plan'),
                        ],
                        '#empty_option' => t('alle'),
                        '#empty_value' => 'all',
                        '#default_value' => [$default_values['status']],
                    ],
                ],
            ],
        ],
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('Filter'),
        '#attributes' => [
            'class' => ['projects-filters-submit element-invisible'],
        ],
    ];


    $view_mode_map = [
        'list' => 'cards',
        'cards' => 'list',
    ];

    list($needPage, $projects) = mkbh_projekter_page_projekter_get_items(1, $view_mode);
    $form['projects'] = [
        '#type' => 'container',
        '#attributes' => [
            'class' => ['col col-md-12 projects-block'],
        ],
        [
            '#type' => 'container',
            '#attributes' => [
                'class' => ['row overflow-hidden'],
            ],
            [
                '#theme' => 'html_tag',
                '#tag' => 'div',
                '#value' => render($projects),
                '#attributes' => [
                    'class' => ['col col-md-12 region-projects-' . $view_mode],
                ],
            ],
        ],
    ];

    $url_q = $_GET;
    unset($url_q['q']);
    $url_q_change_view_m = $url_q;
    $url_q_change_ajax_more = $url_q;
    $url_q_change_ajax_more['view_m'] = $view_mode;
    $url_q_change_view_m['view_m'] = $view_mode_map[$view_mode];

    $view_mode_change_link_title = $view_mode == 'list' ? t('vis store') : t('vis som liste');
    $form['links'] = [
        '#type' => 'container',
        '#attributes' => [
            'class' => ['col col-md-12 region-links'],
        ],
        $needPage === FALSE ? [] : [
            '#theme' => 'link',
            '#text' => t('se alle'),
            '#options' => [
                'html' => TRUE,
                'attributes' => [
                    'class' => ['col col-md-6 more-link use-ajax'],
                ],
                'query' => $url_q_change_ajax_more,
            ],
            '#path' => 'projekter/more/1/' . $view_mode,
        ],
        [
            '#theme' => 'link',
            '#text' => $view_mode_change_link_title,
            '#options' => [
                'html' => TRUE,
                'attributes' => [
                    'class' => ['col col-md-6'],
                ],
                'query' => $url_q_change_view_m,
            ],
            '#path' => $_GET['q'],
        ],
    ];

    return $form;
}

function mkbh_projekter_page_projekter_form_submit($form, &$form_state)
{
    form_state_values_clean($form_state);
    $values = $form_state['values'];
    $view_mode = !isset($_GET['view_m']) ? 'cards' : $_GET['view_m'];
    $form_state['redirect'] = [
        $_GET['q'],
        [
            'query' => [
                'view_m' => $view_mode,
                'sort' => $values['sorting'],
                'city' => $values['bydel'],
                'type' => $values['type'],
                'status' => $values['status'],
            ],
        ],
    ];
}

/**
 * Function for returning items for rendering.
 *
 * @param int $page
 * @param string $view_mode
 *
 * @return array
 */
function mkbh_projekter_page_projekter_get_items($page = 1, $view_mode)
{
    $items = [];
    $locations = [];
    $options = [
        'sort' => isset($_GET['sort']) ? $_GET['sort'] : 'abc',
        'filters' => [
            'district' => isset($_GET['city']) ? $_GET['city'] : 'all',
            'type' => isset($_GET['type']) ? $_GET['type'] : 'all',
            'status' => isset($_GET['status']) ? $_GET['status'] : 'all',
        ],
    ];

    $limit = 70;

    $offset = $limit * ($page - 1);

    $nids = _mkbh_projekter_page_projekter_get_nids($options, $page === 1 ? $limit : 99999, $offset);

    foreach ($nids as $nid) {
        $nw = entity_metadata_wrapper('node', $nid);

        $district = $nw->field_project_city_district->value();
        $type = $nw->field_project_type->value();
        $start_year = $nw->field_project_start_year->value();
        $end_year = $nw->field_project_end_year->value();

        $comments_count = db_select('social_stats_facebook', 'ssf')->fields('ssf', ['fb_comments'])->condition('ssf.nid', $nid);
        $comments_count = $comments_count->execute()->fetchField();

        $status = '';

        if ($start_year && $end_year) {
            $status = t('Afsluttet');
        } elseif ($start_year && !$end_year) {
            $status = t('Under opførsel');
        } elseif (!$start_year && !$end_year) {
            $status = t('Plan');
        }

        $mainImage = $nw->field_project_main_image->value();
        $miWrapper = entity_metadata_wrapper('field_collection_item', $mainImage);

        $image_obj = $miWrapper->field_project_mi_image->value();

        $style_name = $view_mode == 'list' ? '120x120' : '640x320';
        $image = [
            '#theme' => 'image_style',
            '#style_name' => $style_name,
            '#path' => $image_obj['uri'],
        ];

        $location = location_load_locations($nid, 'nid');

        $items[] = [
            'title' => l($nw->title->value(), 'node/' . $nid),
            'district' => $district->name,
            'type' => $type->name,
            'status' => $status,
            'comments_count' => (int)$comments_count,
            'image' => [
                '#theme' => 'link',
                '#text' => render($image),
                '#path' => 'node/' . $nid,
                '#options' => [
                    'attributes' => [],
                    'html' => TRUE,
                ],
            ],
        ];
    }

    if ($view_mode == 'cards') {
        if ($items) {
            $items = array_chunk($items, 2);
        }
    }

    $return = [
      $page == 1,
      [
        '#theme' => 'mkbh_projekter_page_' . $view_mode,
        '#items' => $items,

      ],
    ];

    //For document request
    if (empty($_POST["js"])) {
      $location_settings = mkbh_projekter_location_settings_all();
      $return[1]['#attached'] = [
        'js' => [
          [
            'data' => ['projekter_map_settings' => $location_settings],
            'type' => 'setting',
          ],
        ],
      ];
    }

  return $return;
}


/**
 * Gets all location settings
 *
 * @return array
 *   Settings.
 */
function mkbh_projekter_location_settings_all() {
  $data = mkbh_projekter_get_locations_all();
  $loc_settings = [];
  foreach($data AS $data_key => $data_value){
    $info=  [
      '#theme' => 'mkbh_projekter_page_map_popup',
      '#title' => l($data_value->title, 'node/' . $data_value->nid),
      '#district' => $data_value->name,
    ];

    if(isset($loc_settings[$data_value->nid])){
      continue;
    }

    $loc_settings[$data_value->nid]=[
      'latLng' => [
        $data_value->latitude,
        $data_value->longitude,
      ],
      'info' => render($info),
      'nid' => $data_value->nid,
    ];
  }
  return $loc_settings;
}

/**
 * Gets all project locations at once.
 *
 * @return array
 *   Locations data.
 */
function mkbh_projekter_get_locations_all() {
  $q = db_select('node', 'n')->fields('n')->condition('n.status', 1)->condition('n.type', 'projekt');
  $q->innerJoin('field_data_field_project_city_district', 'district', 'n.nid = district.entity_id');
  $q->innerJoin('taxonomy_term_data', 'd_name', 'district.field_project_city_district_target_id = d_name.tid');
  $q->innerJoin('location_instance', 'li', 'n.nid = li.nid');
  $q->innerJoin('location', 'loc', 'loc.lid = li.lid');
  $q->fields('loc', array('latitude', 'longitude'));
  $q->fields('d_name', array('name'));
  $data = $q->execute()->fetchAll();
  return $data;
}

/**
 * Helper function for getting nids of type "projekt".
 */
function _mkbh_projekter_page_projekter_get_nids($options, $limit, $offset, $count = FALSE)
{
    $sort = $options['sort'];
    $filters = $options['filters'];
    $q = db_select('node', 'n')->fields('n', ['nid'])->condition('n.status', 1)->condition('n.type', 'projekt');
    if ($sort == 'abc') {
        $q->orderBy('n.title', 'ASC');
    } elseif ($sort == 'year') {
        switch ($filters['status']) {
            case 'afsluttet':
                $q->orderBy('start_year.field_project_start_year_value', 'DESC');
                break;
            case 'under_opforsel':
                $q->orderBy('start_year.field_project_start_year_value', 'DESC');
                break;
            case 'plan':
                $q->orderBy('n.title', 'ASC');
                break;
            case 'all':
                $q->leftJoin('field_data_field_project_start_year', 'start_year', 'n.nid = start_year.entity_id');
                $db_or = db_or();
                $db_or->isNull('start_year.field_project_start_year_value');
                $db_or->isNotNull('start_year.field_project_start_year_value');
                $q->condition($db_or);
                $q->orderBy('start_year.field_project_start_year_value', 'DESC');
                break;
        }
    }

    if ($filters['district'] != 'all') {
        $q->innerJoin('field_data_field_project_city_district', 'district', 'n.nid = district.entity_id');
        $q->condition('district.field_project_city_district_target_id', $filters['district']);
    }
    if ($filters['type'] != 'all') {
        $q->innerJoin('field_data_field_project_type', 'type', 'n.nid = type.entity_id');
        $q->condition('type.field_project_type_target_id', $filters['type']);
    }
    if ($filters['status'] != 'all') {
        switch ($filters['status']) {
            case 'afsluttet':
                $q->innerJoin('field_data_field_project_start_year', 'start_year', 'n.nid = start_year.entity_id');
                $q->innerJoin('field_data_field_project_end_year', 'end_year', 'n.nid = end_year.entity_id');
                break;
            case 'under_opforsel':
                $q->innerJoin('field_data_field_project_start_year', 'start_year', 'n.nid = start_year.entity_id');
                $q->leftJoin('field_data_field_project_end_year', 'end_year', 'n.nid = end_year.entity_id');
                $q->isNull('end_year.field_project_end_year_value');
                break;
            case 'plan':
                $q->leftJoin('field_data_field_project_start_year', 'start_year', 'n.nid = start_year.entity_id');
                $q->isNull('start_year.field_project_start_year_value');
                $q->leftJoin('field_data_field_project_end_year', 'end_year', 'n.nid = end_year.entity_id');
                $q->isNull('end_year.field_project_end_year_value');

                break;
        }
    }

    if ($count) {
        $q = $q->execute()->rowCount();
    } else {
        $q->range($offset, $limit);
        $q = $q->execute()->fetchCol();
    }

    return $q;
}

/**
 * Ajax callback for projekter/more/%/% route.
 *
 * @param $page
 * @param $view_mode
 *
 * @return array
 *
 * @see mkbh_projekter_page_menu.
 */
function mkbh_projekter_page_load_more($page, $view_mode)
{
    $page = $page + 1;
    list($need_page, $projects) = mkbh_projekter_page_projekter_get_items($page, $view_mode);
    $commands = [];

    if ($need_page === FALSE) {
        $commands[] = ajax_command_remove('.more-link');
    } else {
        $url_q = $_GET;
        unset($url_q['q']);
        $url_q['view_m'] = $view_mode;
        $new_more_link = [
            '#theme' => 'link',
            '#text' => t('se alle'),
            '#options' => [
                'html' => TRUE,
                'attributes' => [
                    'class' => ['col col-md-6 more-link use-ajax'],
                ],
                'query' => $url_q,
            ],
            '#path' => 'projekter/more/' . $page . '/' . $view_mode,
        ];
        $commands[] = ajax_command_replace('.more-link', render($new_more_link));
    }

    $commands[] = ajax_command_append('.region-projects-' . $view_mode, render($projects));

    return ['#type' => 'ajax', '#commands' => $commands];
}
