<?php
define('_FEXEC', 1);
require('includes/application_top.php');
require_once('includes/functions/categories_lookup.php');
require(DIR_WS_INCLUDES . '/tweak/general.php');
frequire($FSESSION->language.'/event_open_scheduler.php',RLANG);	


// Save new opening time
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_open_at'])) {
  $cid = (int)$_POST['categories_id'];
  $inp = trim($_POST['open_at'] ?? '');

  // Accept "YYYY-MM-DD HH:MM" or "DD-MM-YYYY HHMM"
  $dt = null;
  if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $inp)) {
    $dt = DateTime::createFromFormat('Y-m-d H:i', $inp);
  } else {
    $dt = DateTime::createFromFormat('d-m-Y Hi', $inp); // 16-10-2025 0700
  }

  if ($dt) {
    $iso = $dt->format('Y-m-d H:i:s');

    // Optional policy: only one pending schedule per category (delete older pending)
    tep_db_query("DELETE FROM event_open_schedule 
                   WHERE categories_id = " . (int)$cid . " 
                     AND processed = 0");

    // Insert new schedule
    tep_db_query("INSERT INTO event_open_schedule (categories_id, open_at) 
                  VALUES (" . (int)$cid . ", '" . tep_db_input($iso) . "')");
    $messageStack->add_session('Opening time saved for category ' . $cid . ' ? ' . htmlspecialchars($iso), 'success');
  } else {
    $messageStack->add_session('Invalid date/time. Use "YYYY-MM-DD HH:MM" or "DD-MM-YYYY HHMM".', 'error');
  }
  tep_redirect(tep_href_link(basename(__FILE__)));
}

// Clear schedule (pending only)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['clear_open_at'])) {
  $cid = (int)$_POST['categories_id'];
  tep_db_query("DELETE FROM event_open_schedule 
                 WHERE categories_id = " . (int)$cid . " 
                   AND processed = 0");
  $messageStack->add_session('Pending schedule cleared for category ' . $cid . '.', 'success');
  tep_redirect(tep_href_link(basename(__FILE__)));
}

// // Fetch events (few items ? simple query)
// $events = tep_db_query("
  // SELECT c.categories_id, c.categories_status, c.concert_date_unix, c.date_id
  // FROM " . TABLE_CATEGORIES . " c
  // WHERE (c.concert_date_unix IS NOT NULL AND c.concert_date_unix > 0)
     // OR (c.date_id IS NOT NULL AND c.date_id <> '')
  // ORDER BY IFNULL(c.concert_date_unix, 9999999999)
// ");

$events = tep_db_query("
  SELECT c.categories_id, c.categories_status, c.plan_id, c.concert_date_unix, c.date_id
  FROM " . TABLE_CATEGORIES . " c
  WHERE c.categories_status = 0 AND c.plan_id=3 
    AND (
      (c.concert_date_unix IS NOT NULL AND c.concert_date_unix > 0)
      OR (STR_TO_DATE(TRIM(c.date_id), '%d-%m-%Y %H%i') IS NOT NULL)
    )
  ORDER BY IFNULL(c.concert_date_unix, 9999999999)
");



// Helper: pretty display from unix or date_id (16-10-2025 2000)
function pretty_dt($unix, $date_id) {
  if ((int)$unix > 0) return date('d-m-Y H:i', (int)$unix);
  $dt = DateTime::createFromFormat('d-m-Y Hi', trim($date_id)); // purely for display
  return $dt ? $dt->format('d-m-Y H:i') : htmlspecialchars($date_id);
}

// Load pending schedules in one pass
$pending = [];
$ps = tep_db_query("SELECT categories_id, open_at FROM event_open_schedule WHERE processed = 0");
while ($r = tep_db_fetch_array($ps)) { $pending[(int)$r['categories_id']] = $r['open_at']; }
?>
<!doctype html>
<html <?php echo HTML_PARAMS; ?>>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
  <title><?php echo TITLE; ?></title>
  <link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <style>.mono{font-family:monospace}</style>
</head>
<body>
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<div class="container my-4">
  <h3><i class="bi bi-alarm"></i> <?php echo HEADING_TITLE; ?></h3>
  <p class="text-muted">
    <?php echo TEXT_SCHEDULER_INFO; ?>
  </p>

  <div class="table-responsive">
    <table class="table table-sm table-striped align-middle">
      <thead class="table-light">
        <tr>
          <th>ID</th>
          <th>date_id</th>
          <th><?php echo TEXT_SCHEDULER_STATUS; ?></th>
          <th><?php echo TEXT_SCHEDULER_OPEN; ?></th>
          <th class="text-end"><?php echo TEXT_SCHEDULER_SCHEDULE; ?></th>
        </tr>
      </thead>
      <tbody>
      <?php if (tep_db_num_rows($events) == 0): ?>
        <tr><td colspan="6"><div class="alert alert-warning mb-0"><?php echo TEXT_SCHEDULER_NOEVENTS; ?>.</div></td></tr>
      <?php else: while ($e = tep_db_fetch_array($events)): 
        $cid    = (int)$e['categories_id'];
        $status = $e['categories_status'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>';
        $openAt = $pending[$cid] ?? null;
      ?>
        <tr>
          <td><?php echo $cid; ?></td>
          <td class="mono"><?php echo htmlspecialchars($e['date_id']); ?></td>
          <td><?php echo $status; ?></td>
          <td class="mono">
  <?php if ($openAt): ?>
    <div class="small text-muted"><?php echo htmlspecialchars(format_heading_date($openAt)); ?>
	<?php echo htmlspecialchars(format_heading_time($openAt)); ?></div>
  <?php else: ?>
    <span class="text-muted">—</span>
  <?php endif; ?>
</td>

          <td class="text-end">
		  <?php if (!empty($openAt)): ?>
			<!-- Pending exists: show nothing except Clear -->
			<form method="post" class="d-inline">
			  <input type="hidden" name="categories_id" value="<?php echo (int)$cid; ?>">
			  <button class="btn btn-sm btn-outline-danger" name="clear_open_at" value="1"><?php echo TEXT_SCHEDULER_CLEAR; ?></button>
			</form>
		  <?php else: ?>
			<!-- No pending: show input + Save -->
			<form method="post" class="d-inline-flex gap-2 align-items-center">
			  <input type="hidden" name="categories_id" value="<?php echo (int)$cid; ?>">
			  <input name="open_at" class="form-control form-control-sm mono" style="width:190px"
					 placeholder="e.g. DD-MM-YYYY HHMM">
			  <button class="btn btn-sm btn-primary" name="save_open_at" value="1"><?php echo TEXT_SCHEDULER_SAVE; ?></button>
			</form>
		  <?php endif; ?>
</td>

        </tr>
      <?php endwhile; endif; ?>
      </tbody>
    </table>
  </div>


</div>
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
