<?php
session_start();
$page_title = 'Schedules';
$active_nav = 'schedules';
require_once __DIR__ . '/includes/header.php';

$success = '';
$error   = '';

// ─── Handle POST ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $error = "Security token mismatch."; goto render; }

    $form_action = $_POST['form_action'] ?? '';

    // ─── Create schedule ────────────────────────────────────────────────
    if ($form_action === 'create') {
        $label          = trim($_POST['label']          ?? '');
        $amount         = (float)($_POST['amount']         ?? 0);
        $frequency      = $_POST['frequency']      ?? '';
        $day_of_month   = (int)($_POST['day_of_month']   ?? 1);
        $day_of_week    = (int)($_POST['day_of_week']    ?? 1);
        $notes          = trim($_POST['notes']          ?? '');

        if (!$label)                              { $error = "Schedule label is required."; goto render; }
        if ($amount < 100)                        { $error = "Minimum amount is ₦100."; goto render; }
        if (!in_array($frequency, ['weekly','bi_weekly','monthly'])) { $error = "Invalid frequency."; goto render; }

        $next_run = next_run_date($frequency, $day_of_month, $day_of_week);

        $ins = $conn->prepare(
            "INSERT INTO org_funding_schedules
               (organization_id, created_by, label, amount_per_staff, frequency,
                day_of_month, day_of_week, next_run_at, is_active, notes, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())"
        );
        $ins->bind_param("iisississ", $org_id, $uid, $label, $amount, $frequency, $day_of_month, $day_of_week, $next_run, $notes);
        if ($ins->execute()) {
            $success = "Schedule <strong>" . h($label) . "</strong> created. Next run: " . fmt_date($next_run) . ".";
        } else {
            $error = "Failed to create schedule.";
        }
    }

    // ─── Toggle active ───────────────────────────────────────────────────
    if ($form_action === 'toggle') {
        $sched_id  = (int)($_POST['sched_id'] ?? 0);
        $new_state = (int)($_POST['new_state'] ?? 0);

        $v = $conn->prepare("SELECT id FROM org_funding_schedules WHERE id=? AND organization_id=? LIMIT 1");
        $v->bind_param("ii", $sched_id, $org_id);
        $v->execute();
        if ($v->get_result()->num_rows === 0) { $error = "Schedule not found."; goto render; }

        $upd = $conn->prepare("UPDATE org_funding_schedules SET is_active=? WHERE id=? AND organization_id=?");
        $upd->bind_param("iii", $new_state, $sched_id, $org_id);
        $upd->execute();
        $success = "Schedule " . ($new_state ? "activated" : "paused") . ".";
    }

    // ─── Delete ──────────────────────────────────────────────────────────
    if ($form_action === 'delete') {
        $sched_id = (int)($_POST['sched_id'] ?? 0);
        $del = $conn->prepare("DELETE FROM org_funding_schedules WHERE id=? AND organization_id=?");
        $del->bind_param("ii", $sched_id, $org_id);
        $del->execute();
        $success = "Schedule deleted.";
    }
}

render:

// Load schedules
$schedules = [];
$sq = $conn->prepare(
    "SELECT s.*, u.name AS creator_name
     FROM org_funding_schedules s
     INNER JOIN users u ON s.created_by = u.id
     WHERE s.organization_id = ?
     ORDER BY s.is_active DESC, s.next_run_at ASC"
);
$sq->bind_param("i", $org_id);
$sq->execute();
$schedules = $sq->get_result()->fetch_all(MYSQLI_ASSOC);

$active_count   = count(array_filter($schedules, fn($s) => $s['is_active']));
$inactive_count = count($schedules) - $active_count;
?>

<div class="anim-up">

<!-- Page header -->
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Funding Schedules</h2>
    <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo $active_count; ?> active · <?php echo $inactive_count; ?> paused</p>
  </div>
  <button onclick="openModal('createModal')" class="btn btn-org btn-md">
    <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    New Schedule
  </button>
</div>

<?php if ($success): ?>
<div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg><?php echo $success; ?></div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><?php echo $error; ?></div>
<?php endif; ?>

<!-- Schedule info banner -->
<div class="alert alert-info" style="margin-bottom:20px">
  <svg viewBox="0 0 24 24" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>
  Schedules define the funding pattern. A cron job or admin action runs them on schedule day. Staff count at execution time is used for the actual disbursement.
</div>

<?php if (empty($schedules)): ?>
<div class="card card-body" style="text-align:center;padding:56px 24px">
  <div style="width:52px;height:52px;background:var(--org-accent-bg);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 14px">
    <svg width="24" height="24" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="var(--org-accent)" stroke-linecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
  </div>
  <p style="font-weight:700;margin-bottom:6px">No schedules yet</p>
  <p style="font-size:.82rem;color:var(--text-muted);margin-bottom:16px">Automate recurring meal ticket credits for your staff</p>
  <button onclick="openModal('createModal')" class="btn btn-org btn-md">Create First Schedule</button>
</div>
<?php else: ?>

<div style="display:flex;flex-direction:column;gap:12px">
  <?php foreach ($schedules as $sch): ?>
  <?php
    $days_map = [1=>'Monday',2=>'Tuesday',3=>'Wednesday',4=>'Thursday',5=>'Friday',6=>'Saturday',7=>'Sunday'];
    $freq_label = match($sch['frequency']) {
      'weekly'   => 'Every ' . ($days_map[$sch['day_of_week']] ?? 'week'),
      'bi_weekly' => 'Every other ' . ($days_map[$sch['day_of_week']] ?? 'week'),
      'monthly'  => 'Monthly on the ' . $sch['day_of_month'] . date('S', mktime(0,0,0,0,$sch['day_of_month'],0)),
      default    => ucfirst($sch['frequency'])
    };
    $is_active  = (bool)$sch['is_active'];
    $overdue    = $is_active && $sch['next_run_at'] < date('Y-m-d');
  ?>
  <div class="card" style="border-left:3px solid <?php echo $is_active ? 'var(--org-accent)' : 'var(--border-dark)'; ?>">
    <div class="card-body" style="padding:18px 20px">
      <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap">
        <div style="flex:1">
          <div style="display:flex;align-items:center;gap:10px;margin-bottom:6px;flex-wrap:wrap">
            <span style="font-weight:800;font-size:.95rem"><?php echo h($sch['label']); ?></span>
            <?php if ($is_active): ?>
            <span class="badge badge-success">Active</span>
            <?php else: ?>
            <span class="badge badge-muted">Paused</span>
            <?php endif; ?>
            <?php if ($overdue): ?>
            <span class="badge badge-warning">⚠ Overdue</span>
            <?php endif; ?>
          </div>

          <div style="display:flex;flex-wrap:wrap;gap:16px;font-size:.82rem;color:var(--text-muted)">
            <span>
              <svg width="13" height="13" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" style="vertical-align:middle;margin-right:3px"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 100 7h5a3.5 3.5 0 010 7H6"/></svg>
              <strong style="color:var(--org-accent)"><?php echo fmt_money($sch['amount_per_staff']); ?></strong> per staff
            </span>
            <span>
              <svg width="13" height="13" viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" style="vertical-align:middle;margin-right:3px"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
              <?php echo $freq_label; ?>
            </span>
            <span>
              Next: <strong style="color:<?php echo $overdue?'var(--error)':'var(--text)'; ?>"><?php echo $sch['next_run_at'] ? fmt_date($sch['next_run_at']) : '—'; ?></strong>
            </span>
            <?php if ($sch['last_run_at']): ?>
            <span>Last ran: <?php echo fmt_date($sch['last_run_at']); ?></span>
            <?php endif; ?>
          </div>

          <?php if ($sch['notes']): ?>
          <p style="font-size:.78rem;color:var(--text-muted);margin-top:6px;font-style:italic"><?php echo h($sch['notes']); ?></p>
          <?php endif; ?>
        </div>

        <div style="display:flex;gap:8px;align-items:center;flex-shrink:0">
          <!-- Toggle active/pause -->
          <form method="POST" style="display:inline">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="form_action" value="toggle">
            <input type="hidden" name="sched_id" value="<?php echo $sch['id']; ?>">
            <input type="hidden" name="new_state" value="<?php echo $is_active ? '0' : '1'; ?>">
            <button type="submit" class="btn btn-secondary btn-sm">
              <?php echo $is_active ? '⏸ Pause' : '▶ Activate'; ?>
            </button>
          </form>
          <!-- Delete -->
          <form method="POST" style="display:inline" onsubmit="return confirm('Delete this schedule? This cannot be undone.')">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="form_action" value="delete">
            <input type="hidden" name="sched_id" value="<?php echo $sch['id']; ?>">
            <button type="submit" class="btn btn-secondary btn-sm" title="Delete schedule">
              <svg viewBox="0 0 24 24" stroke-width="2" fill="none" stroke="currentColor" stroke-linecap="round" width="13" height="13"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg>
            </button>
          </form>
        </div>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php endif; ?>

</div>

<!-- Create Schedule Modal -->
<div class="modal-backdrop" id="createModal">
  <div class="modal">
    <div class="modal-header">
      <h3>New Funding Schedule</h3>
      <button class="modal-close" onclick="closeModal('createModal')">
        <svg viewBox="0 0 24 24" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
    <form method="POST">
      <?php echo csrf_field(); ?>
      <input type="hidden" name="form_action" value="create">
      <div class="modal-body">
        <div class="form-group">
          <label>Schedule Label <span style="color:var(--error)">*</span></label>
          <input type="text" name="label" class="form-control" placeholder="e.g. Monthly Meal Allowance" required>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
          <div class="form-group" style="grid-column:1/-1">
            <label>Amount Per Staff (₦) <span style="color:var(--error)">*</span></label>
            <div style="position:relative">
              <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">₦</span>
              <input type="number" name="amount" class="form-control" style="padding-left:30px" placeholder="0.00" min="100" step="0.01" required>
            </div>
          </div>

          <div class="form-group" style="grid-column:1/-1">
            <label>Frequency <span style="color:var(--error)">*</span></label>
            <select name="frequency" class="form-control" id="freqSelect" onchange="updateFreqFields()" required>
              <option value="monthly">Monthly</option>
              <option value="weekly">Weekly</option>
              <option value="bi_weekly">Bi-Weekly (Every 2 Weeks)</option>
            </select>
          </div>

          <!-- Monthly: day of month -->
          <div class="form-group" style="grid-column:1/-1" id="dayOfMonthGroup">
            <label>Day of Month <span style="color:var(--error)">*</span></label>
            <select name="day_of_month" class="form-control">
              <?php for ($d = 1; $d <= 28; $d++): ?>
              <option value="<?php echo $d; ?>" <?php echo $d===1?'selected':''; ?>><?php echo $d . date('S', mktime(0,0,0,0,$d,0)); ?></option>
              <?php endfor; ?>
            </select>
            <p style="font-size:.72rem;color:var(--text-muted);margin-top:4px">Max 28th to avoid month-end issues.</p>
          </div>

          <!-- Weekly/bi-weekly: day of week -->
          <div class="form-group" style="grid-column:1/-1;display:none" id="dayOfWeekGroup">
            <label>Day of Week <span style="color:var(--error)">*</span></label>
            <select name="day_of_week" class="form-control">
              <option value="1">Monday</option>
              <option value="2">Tuesday</option>
              <option value="3">Wednesday</option>
              <option value="4">Thursday</option>
              <option value="5">Friday</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label>Notes (Optional)</label>
          <textarea name="notes" class="form-control" rows="2" placeholder="Internal note about this schedule…"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('createModal')">Cancel</button>
        <button type="submit" class="btn btn-org btn-md">Create Schedule</button>
      </div>
    </form>
  </div>
</div>

<script>
function updateFreqFields() {
  const v  = document.getElementById('freqSelect').value;
  const dm = document.getElementById('dayOfMonthGroup');
  const dw = document.getElementById('dayOfWeekGroup');
  dm.style.display = v === 'monthly' ? 'block' : 'none';
  dw.style.display = v !== 'monthly' ? 'block' : 'none';
}
updateFreqFields();
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
