<?php
// =============================================
// SHARK CRM - Reminders
// =============================================

$filter = isset($_GET['filter']) ? $_GET['filter'] : 'upcoming';
$where  = "r.account_id = $account_id";
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_<?= $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(<?= $r['id'] ?>)">✓</button>
      <?php endif; ?>
      <button class="btn btn-secondary btn-sm" data-permission="edit" onclick="editReminder(<?= $r['id'] ?>)">Edit</button>
      <button class="btn btn-danger btn-sm" data-permission="delete" onclick="deleteReminder(<?= $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="<?= $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>
