<?php
// ============================================================
//  MediCore — Investment
//  File: accounting/investment.php
// ============================================================
$page  = 'accounting/investment';
$title = 'Investment';
require_once '../includes/header.php';

$cur   = $settings['currency'];
$today = today();

// Overall totals
$totalDep  = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM investments WHERE type='deposit'");
$totalWith = (float) db_val("SELECT COALESCE(SUM(amount),0) FROM investments WHERE type='withdraw'");
$netInvest = $totalDep - $totalWith;

// Per-partner summary
$partners = db_rows(
    "SELECT partner,
            SUM(IF(type='deposit', amount,0))  AS deposited,
            SUM(IF(type='withdraw',amount,0))  AS withdrawn,
            SUM(IF(type='deposit', amount,-amount)) AS net
       FROM investments
      GROUP BY partner
      ORDER BY net DESC"
);

// All unique partner names for datalist
$partnerNames = array_column($partners, 'partner');
?>

<!-- ── Page actions ───────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML =
  `<button class="btn btn-primary btn-sm" onclick="openAdd()">
     ➕ Add Transaction
   </button>`;
</script>

<!-- ── Overall summary ────────────────────────────── -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);
            gap:10px;margin-bottom:14px">
  <div class="sc" style="border-top:3px solid var(--accent)">
    <div class="slabel">Total Deposited</div>
    <div class="sval b" style="color:var(--accent)">
      <?= $cur . number_format($totalDep, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">All partners · All time</div>
  </div>
  <div class="sc" style="border-top:3px solid var(--danger)">
    <div class="slabel">Total Withdrawn</div>
    <div class="sval b" style="color:var(--danger)">
      <?= $cur . number_format($totalWith, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">All partners · All time</div>
  </div>
  <div class="sc" style="border-top:3px solid <?= $netInvest >= 0 ? 'var(--brand)' : 'var(--danger)' ?>">
    <div class="slabel">Net Investment</div>
    <div class="sval b" style="color:<?= $netInvest >= 0 ? 'var(--brand)' : 'var(--danger)' ?>">
      <?= $cur . number_format($netInvest, 2) ?>
    </div>
    <div style="font-size:10px;color:var(--text3);margin-top:2px">Deposited − Withdrawn</div>
  </div>
</div>

<!-- ── Per-partner cards ──────────────────────────── -->
<?php if ($partners): ?>
<div style="margin-bottom:14px">
  <div style="font-size:12px;font-weight:600;color:var(--text2);margin-bottom:8px">
    👥 Partner Summary
  </div>
  <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));
              gap:10px">
    <?php foreach ($partners as $p):
      $net   = (float)$p['net'];
      $dep   = (float)$p['deposited'];
      $with  = (float)$p['withdrawn'];
      $pct   = $dep > 0 ? min(100, ($net / $dep) * 100) : 0;
      $cl    = $net >= 0 ? 'var(--accent)' : 'var(--danger)';
      // Generate avatar initials from partner name
      $words = explode(' ', trim($p['partner']));
      $av    = strtoupper(
          substr($words[0], 0, 1) . (isset($words[1]) ? substr($words[1], 0, 1) : '')
      );
    ?>
    <div class="card"
         style="padding:12px 14px;cursor:pointer"
         onclick="filterPartner('<?= htmlspecialchars(addslashes($p['partner'])) ?>')"
         title="Click to filter transactions">
      <div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
        <div style="width:36px;height:36px;border-radius:50%;
                    background:var(--brand);color:#fff;
                    display:flex;align-items:center;justify-content:center;
                    font-size:13px;font-weight:700;flex-shrink:0">
          <?= htmlspecialchars($av) ?>
        </div>
        <div style="font-weight:700;font-size:13px;line-height:1.3">
          <?= htmlspecialchars($p['partner']) ?>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:1fr 1fr;
                  gap:6px;font-size:11px;margin-bottom:8px">
        <div style="background:var(--accent-xlight);padding:5px 7px;
                    border-radius:var(--rsm)">
          <div style="color:var(--accent);font-size:9px;margin-bottom:1px">DEPOSITED</div>
          <div class="mono" style="font-weight:700;color:var(--accent)">
            <?= $cur . number_format($dep, 2) ?>
          </div>
        </div>
        <div style="background:#fde8e8;padding:5px 7px;border-radius:var(--rsm)">
          <div style="color:var(--danger);font-size:9px;margin-bottom:1px">WITHDRAWN</div>
          <div class="mono" style="font-weight:700;color:var(--danger)">
            <?= $cur . number_format($with, 2) ?>
          </div>
        </div>
      </div>
      <!-- Net balance bar -->
      <div style="display:flex;justify-content:space-between;
                  align-items:center;margin-bottom:5px">
        <span style="font-size:10px;color:var(--text3)">Net</span>
        <span class="mono" style="font-weight:800;font-size:13px;color:<?= $cl ?>">
          <?= $cur . number_format($net, 2) ?>
        </span>
      </div>
      <div style="height:4px;background:var(--border);border-radius:2px;overflow:hidden">
        <div style="height:100%;width:<?= max(0,min(100,$pct)) ?>%;
                    background:<?= $cl ?>;border-radius:2px;transition:width .3s">
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
</div>
<?php else: ?>
<div class="al al-i" style="margin-bottom:14px">
  No investment transactions yet. Add your first transaction above.
</div>
<?php endif; ?>

<!-- ── Filter bar ─────────────────────────────────── -->
<div style="display:flex;gap:9px;align-items:center;
            flex-wrap:wrap;margin-bottom:10px">
  <select id="f-partner" onchange="load()"
    style="padding:5px 9px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none;min-width:160px">
    <option value="">All Partners</option>
    <?php foreach ($partnerNames as $n): ?>
    <option value="<?= htmlspecialchars($n) ?>"><?= htmlspecialchars($n) ?></option>
    <?php endforeach; ?>
  </select>
  <select id="f-type" onchange="load()"
    style="padding:5px 9px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
    <option value="">All Types</option>
    <option value="deposit">▲ Deposit</option>
    <option value="withdraw">▼ Withdraw</option>
  </select>
  <input type="date" id="f-from" onchange="load()"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <span style="font-size:11px;color:var(--text3)">to</span>
  <input type="date" id="f-to" onchange="load()"
    style="padding:5px 8px;border:1px solid var(--border);
           border-radius:var(--rsm);font-family:inherit;
           font-size:12px;outline:none">
  <button class="btn btn-sm" onclick="clearFilters()">✕ Clear</button>
</div>

<!-- ── Transactions table ─────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table>
      <thead>
        <tr>
          <th style="width:38px">#</th>
          <th>Partner</th>
          <th style="text-align:center;width:110px">Type</th>
          <th style="text-align:right">Amount</th>
          <th>Date</th>
          <th>Note</th>
          <th style="text-align:center;width:60px">Action</th>
        </tr>
      </thead>
      <tbody id="inv-body">
        <tr><td colspan="7" class="empty-state">Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="inv-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API       = '../api/investments.php';
const CUR       = '<?= addslashes($cur) ?>';
const IS_ADMIN  = <?= is_admin() ? 'true' : 'false' ?>;
const TODAY     = '<?= $today ?>';
const PARTNERS  = <?= json_encode($partnerNames) ?>;

// ── Load transactions ─────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('inv-body');
  tbody.innerHTML =
    '<tr><td colspan="7" class="empty-state">Loading…</td></tr>';

  const r = await apiPost(API, {
    action:  'list',
    partner: document.getElementById('f-partner').value,
    type:    document.getElementById('f-type').value,
    from:    document.getElementById('f-from').value,
    to:      document.getElementById('f-to').value,
  });

  if (!r.success) {
    tbody.innerHTML = `<tr><td colspan="7" class="empty-state"
      style="color:var(--danger)">Error: ${r.error}</td></tr>`;
    return;
  }
  renderRows(r.data);
}

function renderRows(rows) {
  const tbody  = document.getElementById('inv-body');
  const footer = document.getElementById('inv-footer');

  if (!rows.length) {
    tbody.innerHTML =
      '<tr><td colspan="7" class="empty-state">No transactions found.</td></tr>';
    footer.textContent = ''; return;
  }

  let totDep = 0, totWith = 0;
  tbody.innerHTML = rows.map((r, i) => {
    const isDep = r.type === 'deposit';
    const amt   = parseFloat(r.amount || 0);
    if (isDep) totDep += amt; else totWith += amt;

    const typeBadge = isDep
      ? `<span class="badge" style="background:#d4f0e6;color:var(--accent);font-weight:700">
           ▲ Deposit</span>`
      : `<span class="badge" style="background:#fde8e8;color:var(--danger);font-weight:700">
           ▼ Withdraw</span>`;

    // Avatar initials
    const words = r.partner.split(' ');
    const av = (words[0][0] + (words[1]?.[0]||'')).toUpperCase();

    return `<tr>
      <td style="color:var(--text3)">${i + 1}</td>
      <td>
        <div style="display:flex;align-items:center;gap:8px">
          <div style="width:28px;height:28px;border-radius:50%;
                      background:var(--brand);color:#fff;
                      display:flex;align-items:center;justify-content:center;
                      font-size:10px;font-weight:700;flex-shrink:0">
            ${esc(av)}
          </div>
          <span style="font-weight:600">${esc(r.partner)}</span>
        </div>
      </td>
      <td style="text-align:center">${typeBadge}</td>
      <td class="mono" style="text-align:right;font-weight:700;
                               color:${isDep?'var(--accent)':'var(--danger)'}">
        ${isDep?'+':'-'}${CUR}${amt.toFixed(2)}
      </td>
      <td style="color:var(--text2)">${r.date}</td>
      <td style="font-size:11.5px;color:var(--text2)">${esc(r.note||'—')}</td>
      <td style="text-align:center">
        ${IS_ADMIN
          ? `<button class="btn btn-sm btn-danger" style="padding:2px 7px"
                     onclick="delRow(${r.id})">🗑</button>`
          : ''}
      </td>
    </tr>`;
  }).join('');

  const net = totDep - totWith;
  footer.innerHTML =
    `<strong>${rows.length}</strong> transaction(s) &nbsp;·&nbsp;
     Deposited: <strong style="color:var(--accent)">${CUR}${totDep.toFixed(2)}</strong>
     &nbsp;·&nbsp;
     Withdrawn: <strong style="color:var(--danger)">${CUR}${totWith.toFixed(2)}</strong>
     &nbsp;·&nbsp;
     Net: <strong style="color:${net>=0?'var(--accent)':'var(--danger)'}">
            ${CUR}${net.toFixed(2)}
          </strong>`;
}

// ── Filter by partner (from card click) ──────────────────────
function filterPartner(name) {
  document.getElementById('f-partner').value = name;
  load();
  document.querySelector('.card.tw')?.scrollIntoView(
    { behavior:'smooth', block:'start' }
  );
}

function clearFilters() {
  document.getElementById('f-partner').value = '';
  document.getElementById('f-type').value    = '';
  document.getElementById('f-from').value    = '';
  document.getElementById('f-to').value      = '';
  load();
}

// ── Add Transaction modal ─────────────────────────────────────
function openAdd() {
  showModal(`
  <div style="display:flex;flex-direction:column;gap:10px">

    <div class="fg">
      <label>Partner Name *</label>
      <input id="n-partner" list="partner-list"
             placeholder="Type or select partner name"
             autocomplete="off">
      <datalist id="partner-list">
        ${PARTNERS.map(p => `<option value="${esc(p)}">`).join('')}
      </datalist>
      <span style="font-size:10px;color:var(--text3);margin-top:2px">
        Existing partners auto-suggest. Type new name to add a partner.
      </span>
    </div>

    <div class="fg">
      <label>Transaction Type *</label>
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px"
           id="type-group">
        <label id="lbl-dep"
               style="display:flex;align-items:center;gap:7px;
                      padding:9px 12px;border:2px solid var(--accent);
                      border-radius:var(--rsm);cursor:pointer;
                      background:var(--accent-xlight)">
          <input type="radio" name="n-type" value="deposit" checked
                 onchange="highlightType()">
          <span style="font-weight:600;color:var(--accent)">▲ Deposit</span>
        </label>
        <label id="lbl-with"
               style="display:flex;align-items:center;gap:7px;
                      padding:9px 12px;border:2px solid var(--border);
                      border-radius:var(--rsm);cursor:pointer">
          <input type="radio" name="n-type" value="withdraw"
                 onchange="highlightType()">
          <span style="font-weight:600;color:var(--text2)">▼ Withdraw</span>
        </label>
      </div>
    </div>

    <div class="fg2">
      <div class="fg">
        <label>Amount (${CUR}) *</label>
        <input id="n-amount" type="number" step="0.01"
               min="0.01" placeholder="0.00">
      </div>
      <div class="fg">
        <label>Date</label>
        <input id="n-date" type="date" value="${TODAY}">
      </div>
    </div>

    <div class="fg">
      <label>Note</label>
      <input id="n-note" placeholder="Optional description">
    </div>

    <div id="n-err"
         style="color:var(--danger);font-size:11px;display:none"></div>
  </div>

  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;
              border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-primary" onclick="saveRow()">
      💾 Save Transaction
    </button>
  </div>`, '➕ Add Investment Transaction');

  setTimeout(() => document.getElementById('n-partner')?.focus(), 50);
}

function highlightType() {
  const dep  = document.querySelector('input[name="n-type"][value="deposit"]').checked;
  const lblD = document.getElementById('lbl-dep');
  const lblW = document.getElementById('lbl-with');
  lblD.style.borderColor  = dep ? 'var(--accent)' : 'var(--border)';
  lblD.style.background   = dep ? 'var(--accent-xlight)' : 'transparent';
  lblD.querySelector('span').style.color = dep ? 'var(--accent)' : 'var(--text2)';
  lblW.style.borderColor  = !dep ? 'var(--danger)' : 'var(--border)';
  lblW.style.background   = !dep ? '#fde8e8' : 'transparent';
  lblW.querySelector('span').style.color = !dep ? 'var(--danger)' : 'var(--text2)';
}

// ── Save ──────────────────────────────────────────────────────
async function saveRow() {
  const partner = document.getElementById('n-partner').value.trim();
  const type    = document.querySelector('input[name="n-type"]:checked').value;
  const amount  = parseFloat(document.getElementById('n-amount').value) || 0;
  const date    = document.getElementById('n-date').value;
  const note    = document.getElementById('n-note').value.trim();
  const errEl   = document.getElementById('n-err');

  if (!partner) {
    errEl.textContent = '⚠ Partner name is required.';
    errEl.style.display = 'block';
    document.getElementById('n-partner').focus(); return;
  }
  if (amount <= 0) {
    errEl.textContent = '⚠ Enter a valid amount.';
    errEl.style.display = 'block';
    document.getElementById('n-amount').focus(); return;
  }

  const r = await apiPost(API, {
    action: 'add', partner, type, amount, date, note
  });

  if (r.success) {
    closeModal();
    setTimeout(() => location.reload(), 200);
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block';
  }
}

// ── Delete ────────────────────────────────────────────────────
async function delRow(id) {
  if (!confirm('Delete this transaction?\nThis cannot be undone.')) return;
  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) setTimeout(() => location.reload(), 200);
  else alert('⚠ ' + (r.error || 'Delete failed.'));
}

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

document.addEventListener('DOMContentLoaded', load);
</script>

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