<?php
/**
 * app/views/partials/entity-panels.php
 *
 * Expects: $entityType ('lead'|'customer'|'company'), $entityId (int),
 * $notes, $comments, $attachments, $tags (arrays from the controller),
 * and optionally $tasks (leads only).
 *
 * One shared partial so Notes/Comments/Files/Tags work identically
 * everywhere they appear, instead of three near-duplicate copies.
 */
?>
<div class="ab-card">
  <div class="ab-card-header p-0" style="border-bottom:none;">
    <ul class="nav ab-tabs px-3 pt-2">
      <?php if (isset($tasks)): ?><li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#panelTasks">Tasks</a></li><?php endif; ?>
      <li class="nav-item"><a class="nav-link <?= !isset($tasks) ? 'active' : '' ?>" data-bs-toggle="tab" href="#panelNotes">Notes</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#panelComments">Comments</a></li>
      <?php if (isset($emails)): ?><li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#panelEmails">Emails</a></li><?php endif; ?>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#panelFiles">Files</a></li>
      <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#panelTags">Tags</a></li>
    </ul>
  </div>
  <div class="ab-card-body tab-content">

    <?php if (isset($tasks)): ?>
    <div class="tab-pane fade show active" id="panelTasks">
      <form id="abTaskForm" class="row g-2 mb-3">
        <div class="col-7"><input class="form-control form-control-sm" name="title" placeholder="New task..." required></div>
        <div class="col-4"><input type="datetime-local" class="form-control form-control-sm" name="due_at"></div>
        <div class="col-1"><button class="btn btn-primary btn-sm w-100"><i class="bi bi-plus-lg"></i></button></div>
      </form>
      <div id="abTaskList">
        <?php foreach ($tasks as $t): ?>
        <div class="form-check d-flex align-items-center gap-2 mb-2 p-2 border rounded-3 ab-hairline" data-task-id="<?= (int) $t['id'] ?>">
          <input class="form-check-input mt-0 ab-task-toggle" type="checkbox" <?= $t['is_completed'] ? 'checked' : '' ?>>
          <label class="form-check-label flex-fill small <?= $t['is_completed'] ? 'text-decoration-line-through ab-text-faint' : '' ?>">
            <?= e($t['title']) ?><?= $t['due_at'] ? ' <span class="ab-text-faint">— due ' . e(date('M j, g:i A', strtotime($t['due_at']))) . '</span>' : '' ?>
          </label>
          <button class="btn btn-icon btn-light-soft btn-sm ab-task-delete"><i class="bi bi-trash text-danger"></i></button>
        </div>
        <?php endforeach; ?>
        <?php if (empty($tasks)): ?><div class="ab-empty small py-3">No tasks yet.</div><?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <div class="tab-pane fade <?= !isset($tasks) ? 'show active' : '' ?>" id="panelNotes">
      <textarea class="form-control mb-2" id="abNoteInput" rows="3" placeholder="Add a note..."></textarea>
      <button class="btn btn-primary btn-sm mb-3" id="abNoteSaveBtn">Add Note</button>
      <div id="abNoteList">
        <?php foreach ($notes as $n): ?>
        <div class="border-top pt-3 mt-2 ab-divider" data-note-id="<?= (int) $n['id'] ?>">
          <div class="d-flex justify-content-between"><strong class="small"><?= e($n['author_name'] ?? 'Unknown') ?></strong><span class="ab-text-faint small"><?= e(date('M j, g:i A', strtotime($n['created_at']))) ?></span></div>
          <p class="small mb-1"><?= nl2br(e($n['body'])) ?></p>
          <button class="btn btn-link btn-sm text-danger p-0 ab-note-delete">Delete</button>
        </div>
        <?php endforeach; ?>
        <?php if (empty($notes)): ?><div class="ab-empty small py-3">No notes yet.</div><?php endif; ?>
      </div>
    </div>

    <div class="tab-pane fade" id="panelComments">
      <div class="input-group mb-3">
        <input class="form-control" id="abCommentInput" placeholder="Write a comment...">
        <button class="btn btn-primary" id="abCommentSaveBtn">Post</button>
      </div>
      <div id="abCommentList">
        <?php foreach ($comments as $c): ?>
        <div class="d-flex gap-2 mb-3" data-comment-id="<?= (int) $c['id'] ?>">
          <div class="ab-mini-avatar"><?= e(mb_strtoupper(mb_substr($c['author_name'] ?? '?', 0, 1))) ?></div>
          <div class="flex-fill">
            <div class="ab-card p-2" style="background:var(--ab-canvas); border:none;">
              <div class="d-flex justify-content-between"><strong class="small"><?= e($c['author_name'] ?? 'Unknown') ?></strong><span class="ab-text-faint" style="font-size:.7rem;"><?= e(date('M j, g:i A', strtotime($c['created_at']))) ?></span></div>
              <div class="small"><?= nl2br(e($c['body'])) ?></div>
            </div>
            <button class="btn btn-link btn-sm text-danger p-0 ab-comment-delete">Delete</button>
          </div>
        </div>
        <?php endforeach; ?>
        <?php if (empty($comments)): ?><div class="ab-empty small py-3">No comments yet.</div><?php endif; ?>
      </div>
    </div>

    <?php if (isset($emails)): ?>
    <div class="tab-pane fade" id="panelEmails">
      <form id="abSendEmailForm" class="mb-4 p-3 border rounded-3 ab-hairline">
        <div class="mb-2"><label class="form-label ab-req">Subject</label><input class="form-control form-control-sm" name="subject" required></div>
        <div class="mb-2"><label class="form-label ab-req">Message</label><textarea class="form-control form-control-sm" name="body_html" rows="4" required></textarea></div>
        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-send me-1"></i>Send Email</button>
      </form>
      <div id="abEmailList">
        <?php foreach ($emails as $msg): ?>
        <div class="d-flex justify-content-between align-items-start p-2 border-bottom ab-hairline">
          <div><div class="small fw-semibold"><?= e($msg['subject']) ?></div><div class="ab-cell-sub">To: <?= e($msg['to_address']) ?></div></div>
          <div class="text-end">
            <span class="ab-badge <?= $msg['status']==='sent'?'bg-success-soft':'bg-danger-soft' ?>"><?= e(ucfirst($msg['status'])) ?></span>
            <div class="ab-cell-sub"><?= e(date('M j, g:i A', strtotime($msg['created_at']))) ?></div>
          </div>
        </div>
        <?php endforeach; ?>
        <?php if (empty($emails)): ?><div class="ab-empty small py-3">No emails sent yet.</div><?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <div class="tab-pane fade" id="panelFiles">
      <input type="file" id="abFileInput" class="d-none">
      <button class="btn btn-light-soft btn-sm mb-3" id="abFileUploadBtn"><i class="bi bi-upload me-1"></i>Upload File</button>
      <div id="abFileList">
        <?php foreach ($attachments as $a): ?>
        <div class="d-flex align-items-center gap-2 p-2 border-bottom ab-hairline" data-attachment-id="<?= (int) $a['id'] ?>">
          <i class="bi bi-file-earmark-text fs-5 ab-text-muted"></i>
          <div class="flex-fill">
            <a href="<?= e(base_url('uploads-view/' . $a['disk_path'])) ?>" target="_blank" class="small fw-semibold"><?= e($a['original_name']) ?></a>
            <div class="ab-cell-sub"><?= e($a['uploaded_by_name'] ?? '') ?> · <?= e(date('M j, Y', strtotime($a['created_at']))) ?> · <?= number_format($a['size_bytes'] / 1024, 0) ?> KB</div>
          </div>
          <button class="btn btn-icon btn-light-soft btn-sm ab-file-delete"><i class="bi bi-trash text-danger"></i></button>
        </div>
        <?php endforeach; ?>
        <?php if (empty($attachments)): ?><div class="ab-empty small py-3">No files yet.</div><?php endif; ?>
      </div>
    </div>

    <div class="tab-pane fade" id="panelTags">
      <div class="input-group mb-3" style="max-width:320px;">
        <input class="form-control" id="abTagInput" placeholder="Add a tag...">
        <button class="btn btn-primary" id="abTagAddBtn">Add</button>
      </div>
      <div id="abTagList" class="d-flex gap-2 flex-wrap">
        <?php foreach ($tags as $t): ?>
        <span class="ab-chip active" data-tag-id="<?= (int) $t['id'] ?>"><?= e($t['name']) ?> <i class="bi bi-x ms-1 ab-tag-remove" style="cursor:pointer;"></i></span>
        <?php endforeach; ?>
      </div>
    </div>

  </div>
</div>

<script>
(function () {
  var entityType = <?= json_encode($entityType) ?>;
  var entityId = <?= json_encode($entityId) ?>;

  <?php if (isset($emails)): ?>
  document.getElementById('abSendEmailForm').addEventListener('submit', function (e) {
    e.preventDefault();
    var form = e.target;
    var payload = { subject: form.subject.value, body_html: form.body_html.value, to_email: <?= json_encode($entityEmail ?? '') ?> };
    if (entityType === 'lead') payload.related_lead_id = entityId;
    if (entityType === 'customer') payload.related_customer_id = entityId;

    abFetch('<?= base_url('emails/send') ?>', { method: 'POST', body: payload })
      .then(function (res) { abToast(res.message); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abShowFormErrors(form, err.errors); abToast(err.message || 'Send failed.', 'danger'); });
  });
  <?php endif; ?>

  <?php if (isset($tasks)): ?>
  document.getElementById('abTaskForm').addEventListener('submit', function (e) {
    e.preventDefault();
    var form = e.target;
    abFetch('<?= base_url('tasks') ?>', { method: 'POST', body: { lead_id: entityId, title: form.title.value, due_at: form.due_at.value || null } })
      .then(function () { abToast('Task added.'); setTimeout(function () { window.location.reload(); }, 500); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
  document.querySelectorAll('.ab-task-toggle').forEach(function (cb) {
    cb.addEventListener('change', function () {
      var id = this.closest('[data-task-id]').dataset.taskId;
      abFetch('<?= base_url('tasks') ?>/' + id + '/toggle', { method: 'POST', body: { is_completed: this.checked ? 1 : 0 } })
        .then(function () { setTimeout(function () { window.location.reload(); }, 400); });
    });
  });
  document.querySelectorAll('.ab-task-delete').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var wrap = this.closest('[data-task-id]');
      abFetch('<?= base_url('tasks') ?>/' + wrap.dataset.taskId, { method: 'DELETE' }).then(function () { wrap.remove(); });
    });
  });
  <?php endif; ?>

  document.getElementById('abNoteSaveBtn').addEventListener('click', function () {
    var body = document.getElementById('abNoteInput').value.trim();
    if (!body) return;
    abFetch('<?= base_url('notes') ?>', { method: 'POST', body: { entity_type: entityType, entity_id: entityId, body: body } })
      .then(function () { abToast('Note added.'); setTimeout(function () { window.location.reload(); }, 500); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
  document.querySelectorAll('.ab-note-delete').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var el = this.closest('[data-note-id]');
      abFetch('<?= base_url('notes') ?>/' + el.dataset.noteId, { method: 'DELETE' }).then(function () { el.remove(); });
    });
  });

  document.getElementById('abCommentSaveBtn').addEventListener('click', function () {
    var input = document.getElementById('abCommentInput');
    if (!input.value.trim()) return;
    abFetch('<?= base_url('comments') ?>', { method: 'POST', body: { entity_type: entityType, entity_id: entityId, body: input.value.trim() } })
      .then(function () { abToast('Comment posted.'); setTimeout(function () { window.location.reload(); }, 500); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
  document.querySelectorAll('.ab-comment-delete').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var el = this.closest('[data-comment-id]');
      abFetch('<?= base_url('comments') ?>/' + el.dataset.commentId, { method: 'DELETE' }).then(function () { el.remove(); });
    });
  });

  document.getElementById('abFileUploadBtn').addEventListener('click', function () { document.getElementById('abFileInput').click(); });
  document.getElementById('abFileInput').addEventListener('change', function (e) {
    if (!e.target.files.length) return;
    var fd = new FormData();
    fd.append('file', e.target.files[0]);
    fd.append('entity_type', entityType);
    fd.append('entity_id', entityId);
    abFetch('<?= base_url('attachments') ?>', { method: 'POST', body: fd })
      .then(function () { abToast('File uploaded.'); setTimeout(function () { window.location.reload(); }, 600); })
      .catch(function (err) { abToast(err.message || 'Upload failed', 'danger'); });
  });
  document.querySelectorAll('.ab-file-delete').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var el = this.closest('[data-attachment-id]');
      abFetch('<?= base_url('attachments') ?>/' + el.dataset.attachmentId, { method: 'DELETE' }).then(function () { el.remove(); });
    });
  });

  document.getElementById('abTagAddBtn').addEventListener('click', function () {
    var input = document.getElementById('abTagInput');
    if (!input.value.trim()) return;
    abFetch('<?= base_url('tags/attach') ?>', { method: 'POST', body: { entity_type: entityType, entity_id: entityId, tag_name: input.value.trim() } })
      .then(function () { abToast('Tag added.'); setTimeout(function () { window.location.reload(); }, 500); })
      .catch(function (err) { abToast(err.message, 'danger'); });
  });
  document.querySelectorAll('.ab-tag-remove').forEach(function (icon) {
    icon.addEventListener('click', function () {
      var chip = this.closest('[data-tag-id]');
      abFetch('<?= base_url('tags') ?>/' + chip.dataset.tagId + '/detach', { method: 'DELETE', body: { entity_type: entityType, entity_id: entityId } })
        .then(function () { chip.remove(); });
    });
  });
})();
</script>
