<?php
include_once('../header.php');
include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_add_meeting.php');

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

$success        = "none";
$title          = $_data['text_1'];                // Add Meeting
$button_text    = $_data['save_button_text'];      // Save
$successful_msg = $_data['text_15'];               // Saved Successfully
$form_url       = WEB_URL . "meeting/addmeeting.php";

$hdnid               = "0";
$meeting_title       = '';
$meeting_description = '';
$issue_date          = ''; // stored as the next RUN DATE (YYYY-MM-DD)

// --- Helper: compute next date from selected day-of-month ---
function compute_next_monthly_date($day) {
  $day  = max(1, min(31, (int)$day));
  $today = new DateTime('today');

  // Try this month
  $y = (int)$today->format('Y');
  $m = (int)$today->format('n');

  $firstThis = new DateTime("$y-$m-01");
  $lastDayThis = (int)$firstThis->format('t');
  $dThis = min($day, $lastDayThis);
  $candidate = new DateTime(sprintf('%04d-%02d-%02d', $y, $m, $dThis));

  // If already passed, move to next month
  if ($candidate < $today) {
    $firstNext = (clone $firstThis)->modify('+1 month');
    $y2 = (int)$firstNext->format('Y');
    $m2 = (int)$firstNext->format('n');
    $lastDayNext = (int)$firstNext->format('t');
    $dNext = min($day, $lastDayNext);
    $candidate = new DateTime(sprintf('%04d-%02d-%02d', $y2, $m2, $dNext));
  }
  return $candidate->format('Y-m-d');
}

// ---------- Handle POST (add/update) ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $meeting_title       = isset($_POST['txtMeetingTitle']) ? trim($_POST['txtMeetingTitle']) : '';
  $meeting_description = isset($_POST['txtMeetingDesc'])  ? trim($_POST['txtMeetingDesc'])  : '';
  $monthly_day         = isset($_POST['monthlyDay'])      ? (int)$_POST['monthlyDay']       : 1; // 1..31
  $branch_id           = (int)$_SESSION['objLogin']['branch_id'];

  // Compute next run date from chosen day-of-month
  $issue_date = compute_next_monthly_date($monthly_day);

  // Basic required validation
  if ($meeting_title === '') {
    // Fallback alert then stop (keeps UI consistent with your existing pattern)
    echo "<script>alert('".htmlspecialchars($_data['v2'])."');window.history.back();</script>";
    exit();
  }

  if (isset($_POST['hdn']) && $_POST['hdn'] === '0') {
    // INSERT
    $sql = "INSERT INTO `meetings` (meeting_title, meeting_description, issue_date, branch_id)
            VALUES (?, ?, ?, ?)";
    if ($stmt = mysqli_prepare($link, $sql)) {
      mysqli_stmt_bind_param($stmt, "sssi", $meeting_title, $meeting_description, $issue_date, $branch_id);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_close($stmt);
    }
    mysqli_close($link);
    header("Location: " . WEB_URL . "meeting/meetinglist.php?m=add");
    die();
  } else {
    // UPDATE
    $id  = (int)$_POST['hdn'];
    $sql = "UPDATE `meetings`
            SET meeting_title = ?, meeting_description = ?, issue_date = ?
            WHERE meeting_id = ?";
    if ($stmt = mysqli_prepare($link, $sql)) {
      mysqli_stmt_bind_param($stmt, "sssi", $meeting_title, $meeting_description, $issue_date, $id);
      mysqli_stmt_execute($stmt);
      mysqli_stmt_close($stmt);
    }
    header("Location: " . WEB_URL . "meeting/meetinglist.php?m=up");
    die();
  }
}

// ---------- Edit mode (prefill) ----------
if (isset($_GET['id']) && $_GET['id'] !== '') {
  $id = (int)$_GET['id'];
  $result = mysqli_query($link, "SELECT * FROM meetings WHERE meeting_id = $id");
  if ($row = mysqli_fetch_assoc($result)) {
    $meeting_title       = $row['meeting_title'];
    $meeting_description = $row['meeting_description'];
    $issue_date          = $row['issue_date']; // current next-run date

    $hdnid        = $id;
    $title        = $_data['text_16'];            // Update Meeting
    $button_text  = $_data['update_button_text']; // Update
    $successful_msg = $_data['text_17'];          // Updated Successfully
    $form_url     = WEB_URL . "meeting/addmeeting.php?id=$id";
  }
}

// For UI default: if there is an issue date, create a default monthly day from it; else today’s day.
$prefill_day = 1;
if ($issue_date) {
  $prefill_day = (int)date('j', strtotime($issue_date));
} else {
  $prefill_day = (int)date('j');
}
?>
<!-- Content Header -->
<section class="content-header">
  <h1><?= htmlspecialchars($title); ?></h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= $_data['home_breadcam']; ?></a></li>
    <li class="active"><?= $_data['text_2']; ?></li>
    <li class="active"><?= htmlspecialchars($title); ?></li>
  </ol>
</section>

<!-- Styles: clean, modern card UI -->
<style>
  :root{
    --ink:#0b1220; --muted:#64748b; --line:#e5e7eb; --bg:#ffffff;
    --brand:#2563eb; --brand-2:#1e40af; --soft:#f8fafc;
    --ok:#16a34a; --warn:#d97706;
  }
  .meeting-wrap{ max-width: 980px; margin:20px auto; }
  .card{
    background:#fff; border:1px solid var(--line); border-radius:16px;
    box-shadow:0 12px 30px rgba(2,6,23,.07); overflow:hidden;
  }
  .card-header{
    background:linear-gradient(135deg,#f5f7ff,#eef2ff);
    padding:16px 18px; border-bottom:1px solid var(--line);
    display:flex; align-items:center; justify-content:space-between; gap:12px;
  }
  .card-title{ margin:0; font-weight:800; color:#0b1220; letter-spacing:.2px; }
  .card-sub{ margin:0; font-size:12px; color:#475569; }
  .card-body{ padding:18px; }
  .card-footer{ padding:14px 18px; border-top:1px solid var(--line); background:#fff; }

  .form-group label{ font-weight:700; color:#0b1220; margin-bottom:6px; }
  .form-control{
    border-radius:10px; border:1px solid var(--line); padding:10px 12px; height:auto;
    box-shadow:none;
  }
  .form-control:focus{
    border-color:#93c5fd; box-shadow:0 0 0 3px rgba(147,197,253,.35);
  }
  textarea.form-control{ min-height:120px; }

  .inline{ display:flex; gap:12px; align-items:center; flex-wrap:wrap; }
  .hint{ color:#64748b; font-size:12px; }
  .pill{
    display:inline-flex; align-items:center; gap:8px;
    padding:8px 12px; border-radius:999px; background:#eff6ff; color:#1e3a8a;
    border:1px solid #bfdbfe; font-weight:700; font-size:12px;
  }
  .preview{
    font-weight:700; color:#0b1220; background:#f1f5f9; border:1px dashed #cbd5e1;
    border-radius:12px; padding:10px 12px; display:flex; align-items:center; gap:10px;
  }
  .btn{ border-radius:10px; font-weight:800; }
  .btn-success{ background:var(--brand); border-color:var(--brand); }
  .btn-success:hover{ filter:brightness(.97); }
  .btn-warning{ background:#f59e0b; border-color:#f59e0b; }
  .req{ color:#dc2626; }
</style>

<!-- Main content -->
<section class="content meeting-wrap">
  <div class="card">
    <div class="card-header">
      <div>
        <h3 class="card-title"><i class="fa fa-handshake-o"></i> <?= $_data['text_4']; ?></h3>
        <p class="card-sub"><?= $_data['text_6']; ?> &amp; monthly reminder scheduling</p>
      </div>
      <span class="pill"><i class="fa fa-bell-o"></i> Monthly Reminder</span>
    </div>

    <form onsubmit="return validateMe();" action="<?= htmlspecialchars($form_url); ?>" method="post" enctype="multipart/form-data">
      <div class="card-body row">
        <!-- Title -->
        <div class="form-group col-md-12">
          <label for="txtMeetingTitle"><span class="req">*</span> <?= $_data['text_6']; ?>:</label>
          <input type="text" name="txtMeetingTitle" value="<?= htmlspecialchars($meeting_title); ?>" id="txtMeetingTitle" class="form-control" placeholder="e.g., Residents’ Monthly General Meeting" />
        </div>

        <!-- Monthly Day Picker -->
        <div class="form-group col-md-6">
          <label for="monthlyDay"><span class="req">*</span> Monthly Reminder Day:</label>
          <select class="form-control" id="monthlyDay" name="monthlyDay">
            <?php for($d=1; $d<=31; $d++): ?>
              <option value="<?= $d; ?>" <?= ($d === (int)$prefill_day ? 'selected' : ''); ?>><?= $d; ?><?= ($d==1?'st':($d==2?'nd':($d==3?'rd':'th'))); ?></option>
            <?php endfor; ?>
          </select>
          <div class="hint" style="margin-top:6px;">
            If a month has fewer days (e.g., 30 or 28), we’ll automatically use its last day.
          </div>
        </div>

        <!-- Preview (computed) -->
        <div class="form-group col-md-6">
          <label>&nbsp;</label>
          <div class="preview">
            <i class="fa fa-calendar"></i>
            <span>Next reminder on: <span id="nextRunText">—</span></span>
          </div>
          <!-- We still post the ISO date here for the DB -->
          <input type="hidden" id="txtIssueDate" name="txtIssueDate" value="<?= htmlspecialchars($issue_date); ?>">
        </div>

        <!-- Description (optional) -->
        <!-- <div class="form-group col-md-12">
          <label for="txtMeetingDesc"><?= isset($_data['text_66']) ? $_data['text_66'] : 'Description'; ?> (<?= isset($_data['optional']) ? $_data['optional'] : 'optional'; ?>):</label>
          <textarea name="txtMeetingDesc" class="form-control" id="txtMeetingDesc" placeholder="Short notes, agenda, venue, or dial-in link..."><?= htmlspecialchars($meeting_description); ?></textarea>
        </div> -->
      </div>

      <div class="card-footer">
        <div class="form-group pull-right inline">
          <button type="submit" name="button" class="btn btn-success">
            <i class="fa fa-floppy-o"></i> <?= htmlspecialchars($button_text); ?>
          </button>
          <a class="btn btn-warning" href="<?= WEB_URL; ?>meeting/meetinglist.php">
            <i class="fa fa-reply"></i> <?= $_data['back_text']; ?>
          </a>
        </div>
      </div>

      <input type="hidden" value="<?= htmlspecialchars($hdnid); ?>" name="hdn" />
    </form>
  </div>
</section>

<script type="text/javascript">
  // If you want rich text, uncomment CKEditor line below
  // $(document).ready(function(){ CKEDITOR.replace('txtMeetingDesc', { height: 240 }); });

  // Compute next date from selected day-of-month (client-side preview).
  function computeNextDateFromDay(day) {
    day = Math.max(1, Math.min(31, parseInt(day, 10) || 1));
    const today = new Date();
    const y = today.getFullYear();
    const m = today.getMonth(); // 0..11

    function lastDay(year, monthIndex) {
      return new Date(year, monthIndex + 1, 0).getDate();
    }

    // Try this month
    let dThis = Math.min(day, lastDay(y, m));
    let cand = new Date(y, m, dThis);

    // If passed, use next month
    if (cand < new Date(today.getFullYear(), today.getMonth(), today.getDate())) {
      let y2 = y, m2 = m + 1;
      if (m2 > 11) { m2 = 0; y2 += 1; }
      let dNext = Math.min(day, lastDay(y2, m2));
      cand = new Date(y2, m2, dNext);
    }

    return cand;
  }

  function formatISO(d) {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  }

  function formatPretty(d) {
    return d.toLocaleDateString(undefined, { weekday:'short', year:'numeric', month:'short', day:'numeric' });
  }

  function syncNextRun() {
    const daySel = document.getElementById('monthlyDay');
    const nextRun = computeNextDateFromDay(daySel.value);
    document.getElementById('nextRunText').textContent = formatPretty(nextRun);
    document.getElementById('txtIssueDate').value = formatISO(nextRun);
  }

  document.getElementById('monthlyDay').addEventListener('change', syncNextRun);

  // Initialize preview on load:
  (function initPreview(){
    // If editing and server had a date, show that; else compute from default day
    const hiddenDate = document.getElementById('txtIssueDate').value;
    if (hiddenDate) {
      const d = new Date(hiddenDate + 'T00:00:00');
      document.getElementById('nextRunText').textContent = formatPretty(d);
    } else {
      syncNextRun();
    }
  })();

  function validateMe() {
    if (document.getElementById("txtMeetingTitle").value.trim() === '') {
      alert("<?= htmlspecialchars($_data['v2']); ?>");
      document.getElementById("txtMeetingTitle").focus();
      return false;
    }
    // Ensure hidden date is synced
    syncNextRun();
    return true;
  }
</script>
<?php include_once('../footer.php'); ?>
