<?php
if(!defined('access') || access !== 'admincp') die();
NexoraRbac::requirePermission('system.manage');

echo '<h1 class="page-header">Cron Job Manager</h1>';
try {
    $cronManager = new CronManager();

    if(isset($_POST['cron_action'])) {
        $action = (string)$_POST['cron_action'];
        $id = isset($_POST['cron_id']) ? $_POST['cron_id'] : null;
        switch($action) {
            case 'enable': $cronManager->setId($id); $cronManager->enableCron(); break;
            case 'disable': $cronManager->setId($id); $cronManager->disableCron(); break;
            case 'delete': $cronManager->setId($id); $cronManager->deleteCron(); break;
            case 'reset': $cronManager->setId($id); $cronManager->resetCronLastRun(); break;
            case 'allenable': $cronManager->enableAll(); break;
            case 'alldisable': $cronManager->disableAll(); break;
            case 'allreset': $cronManager->resetAllLastRun(); break;
            default: throw new Exception(lang('error_105'));
        }
        NexoraAudit::log('admin.cron_'.$action, 'cron', $id, null, array('action'=>$action));
        message('success', 'Cron actualizado.');
    }

    if(isset($_POST['submit'])) {
        $cronManager->setName($_POST['cron_name']);
        $cronManager->setFile($_POST['cron_file']);
        $cronManager->setInterval($_POST['cron_time']);
        $cronManager->addCron();
        NexoraAudit::log('admin.cron_added', 'cron', $_POST['cron_file'], null, array('interval'=>$_POST['cron_time']));
        message('success', 'Cron agregado.');
    }

    $cronList = $cronManager->getCronList();
    $cronTimes = $cronManager->getCommonIntervals();
    $cronRealm = method_exists($cronManager, 'realm') ? $cronManager->realm() : null;
    $cronRealmLabel = $cronRealm !== null && class_exists('NexoraRealm') ? NexoraRealm::label($cronRealm) : 'Default';
    ?>
    <div class="alert alert-info"><strong>Cadencia aislada por reino:</strong> esta vista muestra el estado de <strong><?php echo htmlspecialchars($cronRealmLabel, ENT_QUOTES, 'UTF-8'); ?></strong>. El timestamp de ejecución ya no se comparte entre Legado y Seasonal.</div>
    <div class="row">
      <div class="col-xs-12 col-lg-4">
        <div class="panel panel-primary"><div class="panel-heading">Agregar tarea</div><div class="panel-body">
          <form action="<?php echo admincp_base('cronmanager'); ?>" method="post">
            <div class="form-group"><label>Nombre</label><input type="text" class="form-control" name="cron_name" required></div>
            <div class="form-group"><label>Archivo</label><select class="form-control" name="cron_file"><?php echo $cronManager->listCronFiles(); ?></select></div>
            <div class="form-group"><label>Frecuencia</label><select class="form-control" name="cron_time">
              <?php foreach((array)$cronTimes as $seconds=>$description) echo '<option value="'.(int)$seconds.'">'.htmlspecialchars($description, ENT_QUOTES, 'UTF-8').'</option>'; ?>
            </select></div>
            <button type="submit" name="submit" value="1" class="btn btn-primary">Agregar</button>
          </form>
        </div></div>
        <div class="panel panel-default"><div class="panel-heading">Acciones globales</div><div class="panel-body">
          <?php foreach(array('allenable'=>'Activar todo','alldisable'=>'Desactivar todo','allreset'=>'Reiniciar tiempos') as $action=>$label) { ?>
            <form method="post" action="<?php echo admincp_base('cronmanager'); ?>" style="display:inline-block;margin:2px"><input type="hidden" name="cron_action" value="<?php echo $action; ?>"><button class="btn btn-xs btn-default" type="submit"><?php echo $label; ?></button></form>
          <?php } ?>
        </div></div>
        <div class="alert alert-info">
          <strong>API segura:</strong> <code><?php echo htmlspecialchars($cronManager->getCronApiUrl(), ENT_QUOTES, 'UTF-8'); ?></code><br>
          Usa <code>POST</code> con <code>Authorization: Bearer &lt;NEXORA_CRON_API_KEY&gt;</code>. El secreto nunca se coloca en la URL.
        </div>
      </div>
      <div class="col-xs-12 col-lg-8">
        <?php if(is_array($cronList)) { ?>
        <div class="table-responsive"><table class="table table-hover"><thead><tr><th>ID</th><th>Nombre</th><th>Archivo</th><th>Frecuencia</th><th>Última ejecución · <?php echo htmlspecialchars($cronRealmLabel, ENT_QUOTES, 'UTF-8'); ?></th><th>Acciones</th></tr></thead><tbody>
        <?php foreach($cronList as $row) { $interval=sec_to_hms($row['cron_run_time']); ?>
          <tr>
            <td><?php echo (int)$row['cron_id']; ?></td>
            <td><?php echo htmlspecialchars($row['cron_name'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td><code><?php echo htmlspecialchars($row['cron_file_run'], ENT_QUOTES, 'UTF-8'); ?></code></td>
            <td><?php echo (int)$interval[0].'h '.(int)$interval[1].'m'; ?></td>
            <td><?php $realmLastRun = isset($row['nexora_realm_last_run']) ? $row['nexora_realm_last_run'] : null; echo $realmLastRun ? date('Y/m/d H:i', $realmLastRun) : '<em>Pendiente</em>'; ?></td>
            <td>
              <?php
              $actions = array('reset'=>'Reset', ((int)$row['cron_status']===1?'disable':'enable')=>((int)$row['cron_status']===1?'Disable':'Enable'), 'delete'=>'Delete');
              foreach($actions as $action=>$label) { ?>
                <form method="post" action="<?php echo admincp_base('cronmanager'); ?>" style="display:inline-block;margin-right:3px"<?php echo $action==='delete'?' onsubmit="return confirm(\'¿Eliminar esta tarea?\')"':''; ?>>
                  <input type="hidden" name="cron_action" value="<?php echo $action; ?>"><input type="hidden" name="cron_id" value="<?php echo (int)$row['cron_id']; ?>">
                  <button type="submit" class="btn btn-xs <?php echo $action==='delete'?'btn-danger':'btn-default'; ?>"><?php echo $label; ?></button>
                </form>
              <?php } ?>
            </td>
          </tr>
        <?php } ?>
        </tbody></table></div>
        <?php } else { message('warning', lang('error_104')); } ?>
      </div>
    </div>
    <?php
} catch(Exception $ex) {
    message('error', $ex->getMessage());
}
