<?php
$calMonth = $_GET['month'] ?? date('Y-m');
$calStart = date('Y-m-01', strtotime($calMonth.'-01'));
$calEnd = date('Y-m-t', strtotime($calStart));
$calQ = $conn->query("SELECT r.*, c.customer_name, l.title lead_title FROM reminder r LEFT JOIN customers c ON c.id=r.customer_id LEFT JOIN leads l ON l.id=r.lead_id WHERE r.account_id=$account_id AND r.date BETWEEN '$calStart' AND '$calEnd' ORDER BY r.date,r.time");
$cal=[]; while($calQ && $rr=$calQ->fetch_assoc()){ $cal[$rr['date']][]=$rr; }
?>
<div class="card" style="padding:16px;margin-bottom:16px">
  <div class="toolbar" style="justify-content:space-between;gap:10px;flex-wrap:wrap">
    <strong>Reminder Calendar - <?= htmlspecialchars(date('F Y', strtotime($calStart))) ?></strong>
    <div class="d-flex gap-8" style="flex-wrap:wrap">
      <a class="btn btn-secondary btn-sm" href="index.php?page=reminders&month=<?= date('Y-m', strtotime($calStart.' -1 month')) ?>">‹ Previous Month</a>
      <a class="btn btn-primary btn-sm" href="index.php?page=reminders&month=<?= date('Y-m') ?>">Current Month</a>
      <a class="btn btn-secondary btn-sm" href="index.php?page=reminders&month=<?= date('Y-m', strtotime($calStart.' +1 month')) ?>">Next Month ›</a>
    </div>
  </div>
  <div class="calendar-week-head"><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span></div>
  <div id="remCalendar" class="calendar-grid">
    <?php $firstDow=(int)date('N',strtotime($calStart)); for($i=1;$i<$firstDow;$i++) echo '<div class="calendar-empty"></div>'; for($d=1;$d<=(int)date('t',strtotime($calStart));$d++): $date=date('Y-m-d',strtotime($calMonth.'-'.$d)); $isToday=$date===date('Y-m-d'); $isSelected=($_GET['date'] ?? '')===$date; ?>
      <div class="calendar-day <?= $isToday?'today':'' ?> <?= $isSelected?'selected':'' ?>" onclick="location.href='index.php?page=reminders&month=<?= $calMonth ?>&date=<?= $date ?>&filter=all'">
        <div class="num"><?= $d ?></div>
        <?php foreach(array_slice($cal[$date]??[],0,3) as $r): ?><span class="calendar-pill"><?= htmlspecialchars(($r['time']?substr($r['time'],0,5).' ':'').($r['customer_name']?:$r['lead_title']?:$r['comment'])) ?></span><?php endforeach; ?>
        <?php if(count($cal[$date]??[])>3): ?><span class="text-xs text-muted">+<?= count($cal[$date])-3 ?> more</span><?php endif; ?>
      </div>
    <?php endfor; ?>
  </div>
</div>
<div id="remListWrap">
<?php
// =============================================
// SHARK CRM - Reminders
// =============================================

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'upcoming';
$where  = "r.account_id = $account_id";
$selectedDate = $_GET['date'] ?? '';
if ($selectedDate && preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $selectedDate)) $where .= " AND r.date='" . $conn->real_escape_string($selectedDate) . "'";
if ($filter === 'upcoming')  $where .= " AND r.status = 'pending' AND r.date >= CURDATE()";
if ($filter === 'overdue')   $where .= " AND r.status = 'pending' AND r.date < CURDATE()";
if ($filter === 'done')      $where .= " AND r.status = 'done'";
if ($filter === 'all')       $where .= "";

$reminders = $conn->query("
  SELECT r.*, c.customer_name, l.title as lead_title, u.name as user_name, at.name as activity_name
  FROM reminder r
  LEFT JOIN customers c ON r.customer_id = c.id
  LEFT JOIN leads l ON r.lead_id = l.id
  LEFT JOIN users u ON r.user_id = u.id
  LEFT JOIN activity_type at ON r.activity_type_id = at.id
  WHERE $where
  ORDER BY r.date ASC, r.time ASC
");

$customers_list  = $conn->query("SELECT id, customer_name FROM customers WHERE account_id=$account_id ORDER BY customer_name");
$leads_list      = $conn->query("SELECT id, title FROM leads WHERE account_id=$account_id AND status='open' ORDER BY datetime_created DESC");
$users_list      = $conn->query("SELECT id, name FROM users WHERE account_id=$account_id ORDER BY name");
$activity_types  = $conn->query("SELECT id, name FROM activity_type");
?>

<div class="fade-in">
<div class="toolbar">
  <div class="d-flex gap-8">
    <?php foreach (['upcoming'=>'Upcoming','overdue'=>'Overdue','done'=>'Done','all'=>'All'] as $k => $v): ?>
    <a href="?page=reminders&filter=<?= $k ?>" class="btn btn-<?= $filter===$k?'primary':'secondary' ?> btn-sm"><?= $v ?></a>
    <?php endforeach; ?>
  </div>
  <button class="btn btn-primary" data-permission="add" style="margin-left:auto" onclick="openModal('addReminderModal')">+ Add Reminder</button>
</div>

<div style="display:grid;gap:10px" id="remindersList">
  <?php if ($reminders->num_rows === 0): ?>
    <div class="empty-state card card-body"><div class="empty-state-icon">🔔</div><p>No reminders found</p></div>
  <?php else: ?>
  <?php while ($r = $reminders->fetch_assoc()):
    $today = date('Y-m-d');
    $cls   = $r['status'] === 'done' ? 'done' : ($r['date'] < $today ? 'overdue' : ($r['date'] == $today ? 'today' : 'upcoming'));
    $color_map = ['overdue' => 'var(--red)', 'today' => 'var(--orange)', 'upcoming' => 'var(--accent)', 'done' => 'var(--text-muted)'];
  ?>
  <div class="reminder-card <?= $cls ?>" id="rem_<?= crmEid($r['id']) ?>">
    <div class="reminder-icon" style="background:<?= $color_map[$cls] ?>22;color:<?= $color_map[$cls] ?>">
      <?= ['Call'=>'📞','Meeting'=>'🤝','Email'=>'📧','WhatsApp'=>'💬','SMS'=>'📱','Note'=>'📝','Follow Up'=>'🔄'][$r['activity_name']] ?? '🔔' ?>
    </div>
    <div class="reminder-body">
      <div class="reminder-title"><?= htmlspecialchars($r['comment'] ?: 'Reminder') ?></div>
      <div class="reminder-meta">
        <?php if ($r['customer_name']): ?>👤 <?= htmlspecialchars($r['customer_name']) ?> · <?php endif; ?>
        <?php if ($r['lead_title']): ?>📊 <?= htmlspecialchars($r['lead_title']) ?> · <?php endif; ?>
        📅 <?= date('M d, Y', strtotime($r['date'])) ?>
        <?php if ($r['time']): ?> at <?= date('H:i', strtotime($r['time'])) ?><?php endif; ?>
        · <?= htmlspecialchars($r['activity_name'] ?? '') ?>
      </div>
    </div>
    <div class="reminder-actions">
      <span class="badge badge-<?= $cls==='overdue'?'red':($cls==='today'?'orange':($cls==='done'?'gray':'teal')) ?>"><?= ucfirst($cls) ?></span>
      <?php if ($r['status'] !== 'done'): ?>
      <button class="btn btn-success btn-sm" data-permission="done" onclick="markDone('<?= crmEid($r['id']) ?>')">✓</button>
      <?php endif; ?>
      <button class="btn btn-secondary btn-sm" data-permission="edit" onclick="editReminder('<?= crmEid($r['id']) ?>')">Edit</button>
      <button class="btn btn-danger btn-sm" data-permission="delete" onclick="deleteReminder('<?= crmEid($r['id']) ?>')">Del</button>
    </div>
  </div>
  <?php endwhile; ?>
  <?php endif; ?>
</div>
</div>

<!-- ADD REMINDER MODAL -->
<div class="modal-overlay" id="addReminderModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title" id="reminderModalTitle">Add Reminder</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body">
      <form id="addReminderForm">
        <input type="hidden" name="edit_id" id="editRemId" value="">
        <div class="form-group">
          <label class="form-label">Comment / Note *</label>
          <textarea name="comment" class="form-control" rows="2" required></textarea>
        </div>
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Date *</label>
            <input type="date" name="date" class="form-control" required value="<?= date('Y-m-d') ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Time</label>
            <input type="time" name="time" class="form-control">
          </div>
          <div class="form-group">
            <label class="form-label">Activity Type</label>
            <select name="activity_type_id" class="form-control">
              <option value="">Select...</option>
              <?php $activity_types->data_seek(0); while ($at = $activity_types->fetch_assoc()): ?>
              <option value="<?= $at['id'] ?>"><?= htmlspecialchars($at['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Assign To</label>
            <select name="user_id" class="form-control">
              <?php $users_list->data_seek(0); while ($u = $users_list->fetch_assoc()): ?>
              <option value="<?= $u['id'] ?>" <?= $u['id']==$user_id?'selected':'' ?>><?= htmlspecialchars($u['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Link to Customer</label>
            <select name="customer_id" class="form-control">
              <option value="">None</option>
              <?php $customers_list->data_seek(0); while ($c = $customers_list->fetch_assoc()): ?>
              <option value="<?= crmEid($c['id']) ?>"><?= htmlspecialchars($c['customer_name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Link to Lead</label>
            <select name="lead_id" class="form-control">
              <option value="">None</option>
              <?php $leads_list->data_seek(0); while ($ld = $leads_list->fetch_assoc()): ?>
              <option value="<?= $ld['id'] ?>"><?= htmlspecialchars($ld['title'] ?: 'Lead #'.$ld['id']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addReminderModal')">Cancel</button>
      <button class="btn btn-primary" data-permission="add" onclick="submitReminder()">Save Reminder</button>
    </div>
  </div>
</div>

<script>
async function submitReminder() {
  const form = document.getElementById('addReminderForm');
  const fd = new FormData(form);
  const editId = document.getElementById('editRemId').value;
  fd.append('action', editId ? 'edit' : 'add');
  const res = await apiCall('handlers/reminders.php', fd);
  if (res.success) {
    showToast(editId ? 'Reminder updated!' : 'Reminder added!', 'success');
    closeModal('addReminderModal');
    setTimeout(() => location.reload(), 600);
  } else showToast(res.message || 'Error', 'error');
}

async function markDone(id) {
  const res = await apiCall('handlers/reminders.php', { action: 'done', id });
  if (res.success) {
    showToast('Marked as done!', 'success');
    const el = document.getElementById('rem_' + id);
    if (el) { el.style.opacity = '0.5'; el.querySelector('.btn-success')?.remove(); }
  } else showToast(res.message || 'Error', 'error');
}

async function editReminder(id) {
  const res = await apiCall('handlers/reminders.php', { action: 'get', id });
  if (!res.success) { showToast('Error', 'error'); return; }
  const r = res.data;
  const f = document.getElementById('addReminderForm');
  f.querySelector('[name=comment]').value          = r.comment || '';
  f.querySelector('[name=date]').value             = r.date;
  f.querySelector('[name=time]').value             = r.time || '';
  f.querySelector('[name=activity_type_id]').value = r.activity_type_id || '';
  f.querySelector('[name=user_id]').value          = r.user_id;
  f.querySelector('[name=customer_id]').value      = r.customer_id || '';
  f.querySelector('[name=lead_id]').value          = r.lead_id || '';
  document.getElementById('editRemId').value       = id;
  document.getElementById('reminderModalTitle').textContent = 'Edit Reminder';
  openModal('addReminderModal');
}

async function deleteReminder(id) {
  confirmAction('Delete this reminder?', async () => {
    const res = await apiCall('handlers/reminders.php', { action: 'delete', id });
    if (res.success) { showToast('Deleted', 'success'); const el = document.getElementById('rem_'+id); if (el) el.remove(); }
    else showToast(res.message || 'Error', 'error');
  });
}
</script>

</div>
<style>
.calendar-week-head{display:grid;grid-template-columns:repeat(7,1fr);gap:8px;margin-top:14px;margin-bottom:6px}.calendar-week-head span{text-align:center;font-size:12px;color:var(--text-muted);font-weight:700}.calendar-grid{display:grid;grid-template-columns:repeat(7,1fr);gap:8px}.calendar-empty{min-height:92px}.calendar-day{min-height:92px;border:1px solid var(--border);border-radius:12px;background:var(--bg-card);padding:8px;cursor:pointer;transition:.15s ease;overflow:hidden}.calendar-day:hover{border-color:var(--accent);box-shadow:0 8px 18px rgba(0,0,0,.08);transform:translateY(-1px)}.calendar-day.today{outline:2px solid var(--accent)}.calendar-day.selected{background:rgba(37,99,235,.08);border-color:var(--accent)}.calendar-day .num{font-weight:800;margin-bottom:6px}.calendar-pill{display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:#eef4ff;color:#1e3a8a;border-radius:999px;padding:3px 7px;font-size:11px;margin-bottom:4px}@media(max-width:800px){.calendar-grid,.calendar-week-head{grid-template-columns:repeat(2,1fr)}.calendar-empty{display:none}}
</style>
