<?php


if (session_status() === PHP_SESSION_NONE) { session_start(); }
date_default_timezone_set('Asia/Kolkata');

/* ------------------------- Centralized config ------------------------- */
$cfgs = [
  __DIR__ . '/config.php',
  __DIR__ . '/../config.php',
  __DIR__ . '/../../config.php'
];
$cfgFound = false;
foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; $cfgFound = true; break; } }
if (!$cfgFound) { http_response_code(500); exit('config.php not found'); }

/* --------------------------- Current user/session --------------------------- */
/* EXACTLY like footer_mobile.php / dst.php */
$ME        = $_SESSION['auth'] ?? [];
$ROLE_ID   = isset($ME['role_id']) ? (int)$ME['role_id'] : 0;   // <-- reference pattern
$ROLE_NAME = strtolower($ME['role_name'] ?? 'user');
$ME_ID     = (int)($ME['id'] ?? 0);
$ME_MAIL   = trim((string)($ME['email'] ?? ''));
$ME_EMPID  = trim((string)($ME['empid'] ?? ''));

/* ------------------------- DB pick & force ONB schema ---------------------- */
$DB = null;
if (isset($conn) && $conn instanceof mysqli)                    { $DB = $conn; }
elseif (isset($conn_crm) && $conn_crm instanceof mysqli)         { $DB = $conn_crm; }
elseif (isset($conn_crmplus) && $conn_crmplus instanceof mysqli) { $DB = $conn_crmplus; }

if (!($DB instanceof mysqli)) { http_response_code(500); exit('DB connection missing.'); }

/* charset/collation */
@mysqli_query($DB, "SET NAMES 'utf8mb4' COLLATE 'utf8mb4_general_ci'");
@mysqli_set_charset($DB, 'utf8mb4');
@mysqli_query($DB, "SET collation_connection='utf8mb4_general_ci'");
@mysqli_query($DB, "USE `broriserin_onb`");


/* ---- Helpers ---- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
function q_one($db,$sql){ $rs=@mysqli_query($db,$sql); if($rs && ($r=mysqli_fetch_assoc($rs))){ @mysqli_free_result($rs); return $r; } return null; }
function q_all($db,$sql){ $o=[]; if($rs=@mysqli_query($db,$sql)){ while($r=mysqli_fetch_assoc($rs)) $o[]=$r; @mysqli_free_result($rs);} return $o; }
function col_exists($db,$t,$c){ $t=mysqli_real_escape_string($db,$t); $c=mysqli_real_escape_string($db,$c); $rs=@mysqli_query($db,"SHOW COLUMNS FROM `{$t}` LIKE '{$c}'"); $ok=$rs && mysqli_num_rows($rs)>0; if($rs) @mysqli_free_result($rs); return $ok; }
function source_badge_style($src){
  $s=strtolower(trim((string)$src));
  $map=['walk'=>'linear-gradient(135deg,#4ea6ff,#1bb0b3);','ref'=>'linear-gradient(135deg,#8b5cf6,#6366f1);','broker'=>'linear-gradient(135deg,#f97316,#ef4444);','web'=>'linear-gradient(135deg,#06b6d4,#3b82f6);','whats'=>'linear-gradient(135deg,#22c55e,#16a34a);','facebook'=>'linear-gradient(135deg,#08f,#0670e8);','insta'=>'linear-gradient(135deg,#f43f5e,#f97316);','google'=>'linear-gradient(135deg,#22d3ee,#818cf8);'];
  foreach($map as $k=>$g){ if (strpos($s,$k)!==false) return $g; }
  return 'linear-gradient(135deg,#0ea5e9,#22c55e);';
}

/* ---- ID + visibility ---- */
$ID = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($ID<=0) { http_response_code(400); exit('Missing id'); }

$vis = "1=1";
if (!in_array($ROLE,['superadmin','admin'],true)) {
  $checks = [];
  if (col_exists($DB,'leads','assigned_user')) {
    $cands = array_values(array_unique(array_filter([$ME_MAIL,$ME_USER,$ME_NAME],'strlen')));
    if ($cands) {
      $esc = array_map(fn($v)=>"'".mysqli_real_escape_string($DB,$v)."'", $cands);
      $checks[] = "assigned_user IN (".implode(',', $esc).")";
    }
  }
  foreach (['empid','employee_id','emp_id'] as $c) {
    if ($ME_EMPID!=='' && col_exists($DB,'leads',$c)) { $checks[] = "`{$c}`='".mysqli_real_escape_string($DB,$ME_EMPID)."'"; break; }
  }
  $vis = $checks ? '('.implode(' OR ',$checks).')' : '0';
}

$rec = q_one($DB,"SELECT * FROM `leads` WHERE id={$ID} AND {$vis} LIMIT 1");
if(!$rec){ http_response_code(404); exit('Lead not found or not visible.'); }

/* ---- Flexible columns ---- */
$contact_name = $rec['contact_name'] ?? ($rec['customer_name'] ?? ($rec['name'] ?? ''));
$project      = $rec['project'] ?? ($rec['project_name'] ?? '');
$phone        = $rec['mobile'] ?? ($rec['phone'] ?? '');
$email        = $rec['email'] ?? '';
$lead_source  = $rec['lead_source'] ?? ($rec['source'] ?? '');
$my_status    = $rec['tags'] ?? '';
$pp_status    = $rec['pp_status'] ?? ($rec['pipeline_stage'] ?? ($rec['stage'] ?? ''));
$comment      = $rec['remarks'] ?? ($rec['note'] ?? ($rec['comment'] ?? ''));
$created_at   = $rec['created_on'] ?? ($rec['created_at'] ?? null);

/* ---- Ensure tables ---- */
@mysqli_query($DB, "CREATE TABLE IF NOT EXISTS `crm_activities` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `enquiry_id` INT UNSIGNED NOT NULL,
  `activity_type` ENUM('call','meeting','task','email') NOT NULL DEFAULT 'task',
  `status` ENUM('Planned','Held','Not Held','Completed','Cancelled') NOT NULL DEFAULT 'Planned',
  `direction` ENUM('Inbound','Outbound','N/A') NOT NULL DEFAULT 'N/A',
  `title` VARCHAR(200) DEFAULT NULL,
  `description` TEXT,
  `date_start` DATETIME DEFAULT NULL,
  `date_end` DATETIME DEFAULT NULL,
  `duration_minutes` INT DEFAULT NULL,
  `assigned_user` VARCHAR(100) DEFAULT NULL,
  `created_by` VARCHAR(100) DEFAULT NULL,
  `remind` TINYINT(1) NOT NULL DEFAULT 0,
  `reminder_at` DATETIME DEFAULT NULL,
  `saved_from` VARCHAR(100) DEFAULT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  KEY `idx_enquiry_id` (`enquiry_id`)
) ENGINE=InnoDB COLLATE=utf8mb4_general_ci");

@mysqli_query($DB,"CREATE TABLE IF NOT EXISTS `crm_pending_actions`(
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `enquiry_id` INT NOT NULL,
  `type` ENUM('call','sms','whatsapp','mail') NOT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `resolved` TINYINT(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`id`),
  KEY `idx_eid_resolved` (`enquiry_id`,`resolved`)
) ENGINE=InnoDB COLLATE=utf8mb4_general_ci");

/* ---- AJAX: save_activity (resolve pending if any) ---- */
if (($_POST['ajax'] ?? '') === 'save_activity') {
  header('Content-Type: application/json');
  $enquiry_id = (int)($_POST['id'] ?? 0);
  if ($enquiry_id !== $ID) { echo json_encode(['ok'=>false,'msg'=>'Invalid context']); exit; }

  $type = strtolower(trim($_POST['type'] ?? 'task'));
  if(!in_array($type,['call','meeting','task','email'],true)) $type='task';

  $status = trim($_POST['status'] ?? 'Planned');
  if(!in_array($status,['Planned','Held','Not Held','Completed','Cancelled'],true)) $status='Planned';

  $direction = trim($_POST['direction'] ?? 'N/A');
  if(!in_array($direction,['Inbound','Outbound','N/A'],true)) $direction='N/A';

  $duration_minutes = max(0,(int)($_POST['duration_minutes'] ?? 5));
  $date_end_raw = trim($_POST['date_end'] ?? '');
  $date_end  = $date_end_raw ? date('Y-m-d H:i:00', strtotime($date_end_raw)) : date('Y-m-d H:i:00');
  $date_start= date('Y-m-d H:i:00', strtotime($date_end) - ($duration_minutes*60));
  $title = trim($_POST['title'] ?? '');
  $description = trim($_POST['description'] ?? '');
  $remind = isset($_POST['remind']) ? (int)$_POST['remind'] : 0;
  $reminder_at_raw = trim($_POST['reminder_at'] ?? '');
  $reminder_at = ($remind && $reminder_at_raw) ? date('Y-m-d H:i:00', strtotime($reminder_at_raw)) : NULL;

  $assigned_user = $rec['assigned_user'] ?? NULL;
  $created_by = $ME_MAIL ?: ($ME_ID ?: null);
  if($title===''){ $title = ucfirst($type).' - '.($email ?: ($contact_name ?: '')); }

  $sql = "INSERT INTO `crm_activities`
    (`enquiry_id`,`activity_type`,`status`,`direction`,`title`,`description`,`date_start`,`date_end`,`duration_minutes`,`assigned_user`,`created_by`,`remind`,`reminder_at`,`saved_from`)
    VALUES (".(int)$enquiry_id.",'".mysqli_real_escape_string($DB,$type)."','".mysqli_real_escape_string($DB,$status)."','".mysqli_real_escape_string($DB,$direction)."','".mysqli_real_escape_string($DB,$title)."','".mysqli_real_escape_string($DB,$description)."','".mysqli_real_escape_string($DB,$date_start)."','".mysqli_real_escape_string($DB,$date_end)."',".(int)$duration_minutes.","
    .($assigned_user===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,$assigned_user)."'").","
    .($created_by===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,(string)$created_by)."'").","
    .(int)$remind.","
    .($reminder_at===NULL ? "NULL" : "'".mysqli_real_escape_string($DB,$reminder_at)."'").",'CRM Lead')";

  $ok = @mysqli_query($DB,$sql);

  if ($ok) {
    $ptype = ($type==='email') ? 'mail' : $type; // pending types: mail/sms/whatsapp/call
    @mysqli_query($DB,"UPDATE crm_pending_actions
                       SET resolved=1
                       WHERE enquiry_id={$ID}
                         AND type='".mysqli_real_escape_string($DB,$ptype)."'
                         AND resolved=0");
  }

  echo json_encode(['ok'=>$ok?true:false]);
  exit;
}

/* ---- Recent activities ---- */
$acts = q_all($DB,"SELECT * FROM `crm_activities` WHERE `enquiry_id`={$ID} ORDER BY `date_end` DESC, `id` DESC LIMIT 30");

/* ---- Pending detector (from dst.php) ---- */
$pending     = q_one($DB,"SELECT * FROM crm_pending_actions WHERE enquiry_id={$ID} AND resolved=0 ORDER BY id DESC LIMIT 1");
$pendingType = $pending ? strtolower($pending['type']) : '';
$recentCut   = date('Y-m-d H:i:s', time()-1200); // 20 min window
$recent      = q_one($DB,"SELECT 1 FROM crm_activities WHERE enquiry_id={$ID} AND date_end>='{$recentCut}' ORDER BY id DESC LIMIT 1");
$autoPromptType = '';
if($pending && !$recent){
  $map = ['call'=>'call','mail'=>'mail','sms'=>'task','whatsapp'=>'task'];
  $autoPromptType = $map[$pendingType] ?? '';
}

/* ---- Contact links (optional) ---- */
$phoneDigits = preg_replace('/\D+/','', $phone);
$telHref  = $phoneDigits ? "tel:{$phoneDigits}" : 'javascript:void(0)';
$mailHref = $email ? ('mailto:'.rawurlencode($email)) : 'javascript:void(0)';

/* ---- UI ---- */
$PAGE_TITLE = 'View DST Lead';
$ASSET = 'assets';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, minimal-ui, viewport-fit=cover">
<title><?php echo h($PAGE_TITLE); ?></title>
<link rel="shortcut icon" type="image/x-icon" href="<?php echo h($ASSET.'/images/favicon.png'); ?>" />
<link rel="stylesheet" href="<?php echo h($ASSET.'/vendor/swiper/swiper-bundle.min.css'); ?>">
<link rel="stylesheet" href="<?php echo h($ASSET.'/css/style.css'); ?>">
<style>
:root{
  --bg:#fff9f5; --card:#ffffff; --muted:#667084; --text:#0f172a; --line:#e9edf5;
  --tile:#fff; --tile-line:#e9edf5; --tile-ring:#4f7cff;
}
body.theme-dark{
  --bg:#0d1117; --card:#141a1f; --muted:#aab2c0; --text:#e9eef7; --line:#242c3b;
  --tile:#fe9063; --tile-line:#273142; --tile-ring:#5b8dff;
}
html,body{background:var(--bg); color:var(--text);}
.card{background:var(--card); border:1px solid var(--line); border-radius:16px;}
.small{color:var(--muted)!important}
.top-back{background:#fff; border:1px solid var(--line); border-radius:10px; padding:.35rem .7rem; font-weight:700}
.tile-rail{display:grid;grid-template-columns:repeat(4,1fr);gap:22px}
.tile{background:var(--tile); border:1px solid var(--tile-line); border-radius:18px; padding:22px 10px; text-align:center; transition:box-shadow .15s,border-color .15s}
.tile:focus,.tile.active{outline:0; border-color:var(--tile-ring); box-shadow:0 0 0 3px color-mix(in srgb, var(--tile-ring) 25%, transparent)}
@keyframes blink{0%,100%{box-shadow:0 0 0 0 rgba(79,124,255,0);}50%{box-shadow:0 0 0 6px rgba(79,124,255,.28);} }
.blink{animation:blink 1.2s linear infinite; border-color:var(--tile-ring)!important}
.tile .tcap{font-weight:700}
.btn-big{background:#4f7cff; color:#fff; border:0; height:50px; border-radius:12px; font-weight:800}
.section{padding:10px 0}
.tile-rail .tile[href] {color: black !important;}
</style>
</head>
<body>
<div class="page-wraper header-fixed">
  <?php include __DIR__.'/header_mobile.php'; ?>
  <?php include __DIR__.'/sidebar_mobile.php'; ?>

  <div class="page-content">
    <div class="container">

      <div class="my-2">
        <a href="/brocrm/mobile/dst.php" class="top-back"><i class="fa-solid fa-arrow-left"></i> Back</a>
      </div>

      <!-- Header Card -->
      <div class="card mb-3">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <div class="small">LEAD<?php echo str_pad((string)$ID,6,'0',STR_PAD_LEFT); ?></div>
              <h5 class="mb-1 fw-extrabold"><?php echo h(trim($contact_name.($project?' – '.$project:'')) ?: '—'); ?></h5>
              <div class="small">
                <?php if($created_at): ?>Created on: <?php echo h(date('d M Y', strtotime($created_at))); ?><?php endif; ?>
              </div>
            </div>
            <?php $srcStyle='background:'.source_badge_style($lead_source).';color:#fff;border:0;'; ?>
            <span class="badge" style="<?php echo h($srcStyle); ?>"><?php echo h($lead_source ?: 'Source N/A'); ?></span>
          </div>
        </div>
      </div>

      <!-- Tiles (blink & auto-open support) -->
      <?php
        $blinkTile = [
          'call'     => ($pendingType==='call' && !$recent) ? ' blink' : '',
          'mail'     => ($pendingType==='mail' && !$recent) ? ' blink' : '',
          'task'     => (($pendingType==='sms' || $pendingType==='whatsapp') && !$recent) ? ' blink' : '',
        ];
        $phoneDigits = preg_replace('/\D+/', '', $phone);
        $telHref  = $phoneDigits ? "tel:{$phoneDigits}" : 'javascript:void(0)';
        $smsHref  = $phoneDigits ? "sms:{$phoneDigits}" : 'javascript:void(0)';
        $waHref   = $phoneDigits ? "https://wa.me/{$phoneDigits}" : 'javascript:void(0)';
      ?>
      <div class="tile-rail mb-3">
        <button class="tile qa<?php echo $blinkTile['call']; ?>" data-action="call" title="Log Call">
          <div class="mb-1"><i class="fa-solid fa-phone"></i></div><div class="tcap">Call</div>
        </button>
        <a href="<?= h($waHref) ?>" class="tile <?= ($pendingType === 'whatsapp' && !$recent) ? ' blink' : '' ?>" data-action="whatsapp" title="WhatsApp" target="_blank" style="color: black;">
          <div class="mb-1"><i class="fab fa-whatsapp"></i></div><div class="tcap">WhatsApp</div>
        </a>
        <a href="<?= h($smsHref) ?>" class="tile <?= ($pendingType === 'sms' && !$recent) ? ' blink' : '' ?>" data-action="sms" title="SMS" style="color: black;">
          <div class="mb-1"><i class="fa-regular fa-message"></i></div><div class="tcap">SMS</div>
        </a>
        <button class="tile qa<?php echo $blinkTile['mail']; ?>" data-action="mail" title="Log Mail">
          <div class="mb-1"><i class="fa-solid fa-envelope"></i></div><div class="tcap">Mail</div>
        </button>
      </div>

      <!-- Status block -->
      <div class="card section">
        <div class="card-body">
          <div class="row g-3">
            <div class="col-12 col-md-6">
              <div class="small">My Status</div>
              <div class="fw-bold"><?php echo h($my_status ?: '—'); ?></div>
            </div>
            <div class="col-12 col-md-6">
              <div class="small">Opportunity Status</div>
              <?php
                $opp = $pp_status;
                if (strcasecmp($my_status,'Prospect')===0 && (strcasecmp($opp,'New')===0 || $opp==='')) $opp='Prospecting';
              ?>
              <div class="fw-bold"><?php echo h($opp ?: '—'); ?></div>
            </div>
            <div class="col-12">
              <div class="small">Comment</div>
              <div class="fw-bold"><?php echo ($comment!=='') ? nl2br(h($comment)) : '—'; ?></div>
            </div>
          </div>
          <a class="btn btn-big w-100 mt-3" href="/brocrm/mobile/dst_crm_edit.php?id=<?php echo (int)$ID; ?>">Edit</a>
        </div>
      </div>

      <!-- Activities -->
      <div class="card mb-5">
        <div class="card-header d-block"><h5 class="card-title mb-0">Recent Activities</h5></div>
        <div class="card-body">
          <?php if(!$acts){ ?>
            <div class="small">No activities yet.</div>
          <?php } else { foreach($acts as $a){ ?>
            <div class="d-flex justify-content-between align-items-start py-2 border-bottom">
              <div>
                <div class="fw-bold text-capitalize"><?php echo h($a['activity_type']); ?></div>
                <div class="small"><?php echo h($a['title'] ?: '—'); ?></div>
                <div class="small">
                  <?php echo h(date('d M Y, h:i A', strtotime($a['date_end']))); ?> •
                  <?php echo h($a['status']); ?>
                  <?php if($a['direction'] && $a['direction']!=='N/A') echo ' • '.h($a['direction']); ?>
                </div>
              </div>
              <div class="small"><?php echo (int)$a['duration_minutes']; ?>m</div>
            </div>
          <?php } } ?>
        </div>
      </div>

    </div>
  </div>

  <?php include __DIR__.'/footer_mobile.php'; ?>
</div>

<!-- Log Activity bottom sheet -->
<div class="offcanvas offcanvas-bottom" tabindex="-1" id="actSheet" style="height:80vh;">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="actTitle">Log Activity</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <div class="card"><div class="card-body">
      <div class="row g-2">
        <div class="col-6">
          <label class="small">Status
            <select id="f-status" class="form-select">
              <option>Planned</option><option>Held</option><option>Not Held</option><option>Completed</option><option>Cancelled</option>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Direction
            <select id="f-direction" class="form-select">
              <option>Outbound</option><option>Inbound</option><option selected>N/A</option>
            </select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Duration (mins)
            <select id="f-duration" class="form-select"><option>5</option><option>15</option><option>30</option><option>45</option><option>60</option><option>90</option><option>120</option></select>
          </label>
        </div>
        <div class="col-6">
          <label class="small">Date End *
            <input id="f-dateend" type="datetime-local" class="form-control">
          </label>
        </div>
        <div class="col-12">
          <label class="small">Title
            <input id="f-title" type="text" class="form-control" placeholder="Title">
          </label>
        </div>
        <div class="col-12">
          <label class="small">Description
            <textarea id="f-desc" rows="4" class="form-control" placeholder="Notes"></textarea>
          </label>
        </div>
        <div class="col-6 d-flex align-items-center">
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="f-remind">
            <label class="form-check-label small" for="f-remind">Set Reminder</label>
          </div>
        </div>
        <div class="col-6">
          <label class="small">Reminder At
            <input id="f-remindat" type="datetime-local" class="form-control" disabled>
          </label>
        </div>
        <div class="col-6">
          <button class="btn btn-big w-100" id="saveAct">Save</button>
        </div>
        <div class="col-6">
          <button class="btn btn-secondary w-100" data-bs-dismiss="offcanvas">Close</button>
        </div>
      </div>
    </div></div>
  </div>
</div>

<script src="<?php echo h($ASSET.'/js/jquery.js'); ?>"></script>
<script src="<?php echo h($ASSET.'/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'/vendor/swiper/swiper-bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'/js/custom.js'); ?>"></script>
<script>
/* Logger sheet */
const sheetEl=document.getElementById('actSheet');
const sheet = sheetEl ? new bootstrap.Offcanvas(sheetEl) : null;
const titleEl=document.getElementById('actTitle');
const endEl=document.getElementById('f-dateend');
const remindCb=document.getElementById('f-remind');
const remindAt=document.getElementById('f-remindat');

function openSheet(kind){
  titleEl.textContent='Log '+(kind==='call'?'Call':kind==='meeting'?'Meeting':kind==='mail'?'Email':'Task');
  const dir=document.getElementById('f-direction');
  dir.disabled=(kind!=='call');
  dir.value=(kind==='call'?'Outbound':'N/A');
  const d=new Date(Date.now()+5*60000);
  const iso=new Date(d.getTime()-d.getTimezoneOffset()*60000).toISOString().slice(0,16);
  endEl.value=iso;
  sheet?.show();
}
remindCb.addEventListener('change',()=>{remindAt.disabled=!remindCb.checked; if(remindCb.checked && !remindAt.value){remindAt.value=endEl.value;}});

let actType='task';
document.querySelectorAll('.qa').forEach(b=>{
  b.addEventListener('click', ()=>{ actType=b.getAttribute('data-action')||'task'; openSheet(actType); });
});

/* Auto-open if a pending action exists and no recent activity */
<?php if($autoPromptType){ ?>
document.addEventListener('DOMContentLoaded', function(){
  actType = '<?php echo $autoPromptType; ?>';
  openSheet(actType);
});
<?php } ?>

/* Save activity (resolve pending on server) */
document.getElementById('saveAct').addEventListener('click',(e)=>{
  e.preventDefault();
  const data=new URLSearchParams();
  data.append('ajax','save_activity');
  data.append('id','<?php echo (int)$ID; ?>');
  data.append('type',actType);
  data.append('status',document.getElementById('f-status').value);
  const dirEl=document.getElementById('f-direction');
  data.append('direction',dirEl.disabled?'N/A':dirEl.value);
  data.append('duration_minutes',document.getElementById('f-duration').value||'5');
  data.append('date_end',(document.getElementById('f-dateend').value||'').replace('T',' '));
  data.append('title',document.getElementById('f-title').value||'');
  data.append('description',document.getElementById('f-desc').value||'');
  data.append('remind',document.getElementById('f-remind').checked?'1':'0');
  data.append('reminder_at',(document.getElementById('f-remindat').value||'').replace('T',' '));
  fetch(location.href,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:data.toString()})
    .then(r=>r.json()).then(j=>{ if(j&&j.ok){ alert('Activity saved'); location.reload(); } else { alert('Failed'); }});
});

/* Visual active ring on tiles */
document.querySelectorAll('.tile-rail .tile').forEach(el=>{
  el.addEventListener('focus',()=>{ el.classList.add('active'); },true);
  el.addEventListener('blur',()=>{ el.classList.remove('active'); },true);
  el.addEventListener('click',()=>{ document.querySelectorAll('.tile-rail .tile').forEach(x=>x.classList.remove('active')); el.classList.add('active'); });
});
</script>
</body>
</html>
