<?php

define('CONTENT_TYPE_NAME', 'notificaciones_por_estado');
/**
 * Implements hook_cron().
 */
function policia_notificaciones_por_estado_cron() {
    try {
        $now = date("Y-m-d H:i:s");
        $query = new EntityFieldQuery();
        $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', CONTENT_TYPE_NAME)
        ->propertyCondition('status', NODE_PUBLISHED)
        ->fieldCondition('field_ne_datetime_active', 'value2', $now, '<=');
        $result = $query->execute();
        if (!empty($result['node'])) {
            $results = array_keys($result['node']);
        }
        $nodes = node_load_multiple($results);
        $nids_delete = [];
        foreach($nodes as $node) {
            $file = file_load($node->field_ne_file['und'][0]['fid']);
            $uri = $file->uri;
            $url = file_create_url($uri);
            $user = user_load($node->uid);
            $fields = [
                'name' => $node->field_ne_nombre['und'][0]['safe_value'],
                'datetime_publish' => $node->field_ne_datetime_active['und'][0]['value'],
                'datetime_unpublish' => $node->field_ne_datetime_active['und'][0]['value2'],
                'act_type' => $node->field_ne_admin_act_type['und'][0]['safe_value'],
                'link_file' => $url,
                'user_upload' => $user->name
            ];
            $nid = db_insert('status_notification_history')
            ->fields($fields)
            ->execute();
            if ($nid) {
                array_push($nids_delete, $node->nid);
                file_delete($file, TRUE);
            }
        }
        node_delete_multiple($nids_delete);
        watchdog('Notificaciones por estado', "Nodos eliminados correctamente.", NULL, WATCHDOG_INFO);
    }
    catch (Exception $e) {
        watchdog('Notificaciones por estado', $e->getMessage(), NULL, WATCHDOG_ERROR);
    }
}

/**
 * Implements hook_menu().
 */
function policia_notificaciones_por_estado_menu(){
    $items['admin/config/administration/notificaciones-por-estado-history'] = [
        'title' => t('History "Notificaciones por estado"'),
        'description' => t('Muestra historica de las notificaciones por estado.'),
        'page callback' => 'policia_notificaciones_por_estado_render_historic',
        'file' => 'includes/policia_notificaciones_por_estado_historic.inc',
        'type' => MENU_CALLBACK,
        'access arguments' => ['administer historic status notifications configuration'],
        'weight' => 1
    ];
    return $items;
}

/**
 * Implements hook_permission().
 */
function policia_notificaciones_por_estado_permission() {
    return [
        'administer historic status notifications configuration' => ['title' => t('Consultar Historico de Notificaciones por estado'), 'restrict access' => TRUE],
    ];
}