<?php
/* =============================================================================
 * File   : crm_view.php
 * Goal   : View a single CRM enquiry/lead with Soziety theme wrapper, quick
 *          actions (Phone/SMS/WhatsApp/Mail) using themed buttons and icons,
 *          plus an activity logger (auto-prompts after external actions).
 * Stack  : Core PHP + MySQLi. Uses config.php via auth_bootstrap.php
 * Auth   : sa_require_auth(); user from $_SESSION['auth']
 * DB     : Auto-detect CRM table. Activities in `crm_activities`
 * Extra  : Uses/creates `crm_pending_actions` for cross-page pending prompts
 * Theme  : Soziety XHTML (assets/**). Light by default; body.theme-dark flips.
 * ============================================================================= */

@session_start();
date_default_timezone_set('Asia/Kolkata');

/* ----------------------- Auth & DB bootstrap ----------------------- */
require_once __DIR__ . '/auth_bootstrap.php'; // provides $DB (any working mysqli), h(), and auth helpers
sa_require_auth();

$ME    = $_SESSION['auth'] ?? [];
$ROLE  = strtolower($ME['role_name'] ?? 'user');
$ME_ID = (int)($ME['id'] ?? 0);

/* Prefer a dedicated CRM link if present */
$DB = isset($conn_crm) && ($conn_crm instanceof mysqli) ? $conn_crm : (isset($DB) && $DB instanceof mysqli ? $DB : null);
if (!($DB instanceof mysqli)) { http_response_code(500); exit('DB connection missing.'); }

@mysqli_set_charset($DB,'utf8mb4');
@mysqli_query($DB,"SET NAMES 'utf8mb4'");
@mysqli_query($DB,"SET collation_connection='utf8mb4_general_ci'");

/* ----------------------- Helpers ----------------------- */
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 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 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 table_exists($db,$t){ $t=mysqli_real_escape_string($db,$t); $rs=@mysqli_query($db,"SHOW TABLES LIKE '{$t}'"); $ok=($rs && mysqli_num_rows($rs)>0); if($rs) @mysqli_free_result($rs); return $ok; }
function owner_col($db,$t){ foreach(['assigned_to','owner_id','user_id','created_by'] as $c){ if(col_exists($db,$t,$c)) return $c; } return ''; }
function r_where($db,$t,$role,$uid){
  $own = owner_col($db,$t);
  if(!$own) return '';
  if(in_array($role,['superadmin','admin'],true)) return '';
  return " AND `$own`=".(int)$uid." ";
}

/* ----------------------- Ensure pending-actions table ----------------------- */
@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");

/* ----------------------- Find CRM table ---------------------------- */
$CRM_TABLE = null;
foreach (['crm_enquiries','crm_leads','enquiries','leads','crm'] as $try){
  if (table_exists($DB,$try)) { $CRM_TABLE = $try; break; }
}
if(!$CRM_TABLE){ http_response_code(500); exit('CRM table not found.'); }

/* ----------------------- Get id & record --------------------------- */
$ID = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if($ID<=0){ http_response_code(400); exit('Missing id'); }
$vis = r_where($DB,$CRM_TABLE,$ROLE,$ME_ID);
$rec = q_one($DB,"SELECT * FROM `{$CRM_TABLE}` WHERE `id`={$ID} {$vis} LIMIT 1");
if(!$rec){ http_response_code(404); exit('Enquiry not found or not visible.'); }

/* Flexible columns */
$F = [
  'name'        => null,
  'mobile'      => null,
  'email'       => null,
  'status'      => null,
  'pp_status'   => null,
  'project'     => null,
  'comment'     => null,
  'assigned_to' => owner_col($DB,$CRM_TABLE) ?: null,
  'created_at'  => col_exists($DB,$CRM_TABLE,'created_at')?'created_at':(col_exists($DB,$CRM_TABLE,'created_on')?'created_on':null),
  'badge'       => null
];
foreach(['name','customer_name','contact_name','lead_name'] as $c){ if(isset($rec[$c])){ $F['name']=$c; break; } }
foreach(['mobile','phone','phone_no','contact'] as $c){ if(isset($rec[$c])){ $F['mobile']=$c; break; } }
foreach(['email','email_id'] as $c){ if(isset($rec[$c])){ $F['email']=$c; break; } }
foreach(['status','my_status'] as $c){ if(isset($rec[$c])){ $F['status']=$c; break; } }
foreach(['pp_status','stage','ppstage'] as $c){ if(isset($rec[$c])){ $F['pp_status']=$c; break; } }
foreach(['project','project_name'] as $c){ if(isset($rec[$c])){ $F['project']=$c; break; } }
foreach(['remarks','note','comment','comments'] as $c){ if(isset($rec[$c])){ $F['comment']=$c; break; } }
foreach(['badge','lead_type','source_type'] as $c){ if(isset($rec[$c])){ $F['badge']=$c; break; } }
$VAL = fn($key) => $F[$key] ? trim((string)$rec[$F[$key]]) : '';

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

/* ----------------------- AJAX: save_activity ------------------------------- */
if(isset($_POST['ajax']) && $_POST['ajax']==='save_activity'){
  header('Content-Type: application/json');

  $lead_id = (int)($_POST['id'] ?? 0);
  if($lead_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 = $VAL('assigned_to') ?: NULL;
  $created_by = $ME['name'] ?? ($ME_ID ?: null);
  if($title===''){ $title = ucfirst($type).' - '.$VAL('name'); }

  $sql = "INSERT INTO `crm_activities`
  (`lead_id`,`activity_type`,`status`,`direction`,`title`,`description`,`date_start`,`date_end`,`duration_minutes`,`assigned_user`,`created_by`,`remind`,`reminder_at`,`saved_from`)
  VALUES (".(int)$lead_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 Enquiry')";
  $ok = @mysqli_query($DB,$sql);

  if($ok){
    $ptype = ($type==='email') ? 'mail' : $type;
    @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'=>true,'id'=>mysqli_insert_id($DB)]);
  } else {
    echo json_encode(['ok'=>false,'msg'=>'DB error','err'=>mysqli_error($DB),'sql'=>$sql]);
  }
  exit;
}

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

/* ----------------------- Pending action brain ----------------------------- */
$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);
$recent      = q_one($DB,"SELECT 1 FROM crm_activities WHERE lead_id={$ID} AND date_end>='{$recentCut}' ORDER BY id DESC LIMIT 1");
$autoPromptType = '';
if($pending && !$recent){
  $map = ['call'=>'call','sms'=>'task','whatsapp'=>'task','mail'=>'email'];
  $autoPromptType = $map[$pendingType] ?? '';
}

/* ----------------------- Contact links ----------------------------- */
$phone = preg_replace('/\D+/','', ($VAL('mobile') ?: ''));
$email = $VAL('email');
$telHref  = $phone ? "tel:{$phone}" : 'javascript:void(0)';
$smsHref  = $phone ? "sms:{$phone}" : 'javascript:void(0)';
$waHref   = $phone ? "https://wa.me/{$phone}" : 'javascript:void(0)';
$mailHref = $email ? ('mailto:'.rawurlencode($email)) : 'javascript:void(0)';

/* Blink helpers for external buttons */
$blinkCall = ($pendingType==='call') ? ' blink' : '';
$blinkSMS  = ($pendingType==='sms') ? ' blink' : '';
$blinkWA   = ($pendingType==='whatsapp') ? ' blink' : '';
$blinkMail = ($pendingType==='mail') ? ' blink' : '';
$blinkTile = [
  'call'     => ($pendingType==='call') ? ' blink' : '',
  'mail'     => ($pendingType==='mail') ? ' blink' : '',
  'task'     => ($pendingType==='sms' || $pendingType==='whatsapp') ? ' blink' : '',
  'meeting'  => '',
];

/* ----------------------- Page bits -------------------------- */
$PAGE_TITLE = 'View Enquiry';
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Meta -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, minimal-ui, viewport-fit=cover">
  <meta name="theme-color" content="#2196f3">
  <title><?php echo h($PAGE_TITLE); ?></title>

  <!-- Soziety CSS -->
  <link rel="shortcut icon" type="image/x-icon" href="assets/images/favicon.png" />
  <link rel="stylesheet" type="text/css" href="assets/css/style.css">
  <link rel="stylesheet" href="assets/vendor/swiper/swiper-bundle.min.css">

  <style>
    :root{
      --safe: env(safe-area-inset-bottom, 0px);
      --bg:#f6f7fb; --card:#ffffff; --card2:#f2f4f8;
      --muted:#6b7380; --text:#121417; --line:#e5e8ef; --primary:#2196f3;
    }
    body.theme-dark{
      --bg:#0d0f14; --card:#171b21; --card2:#10141b;
      --muted:#9aa4b5; --text:#eaeef6; --line:#222833; --primary:#2196f3;
    }
    html,body{background:var(--bg); color:var(--text);}
    .crm-wrap .card{background:var(--card); border:1px solid var(--line); border-radius:16px;}
    .crm-wrap .small{color:var(--muted);}
    .crm-title{font-weight:800}
    .kv{display:grid;grid-template-columns:120px 1fr; gap:8px 12px}
    .kv .k{color:var(--muted); font-size:13px}
    .kv .v{font-weight:800}
    .banner{border:1px dashed #d9a078;border-radius:12px;padding:12px;background:#fff3eb;color:#663400}
    body.theme-dark .banner{border-color:#4e596b;background:#141a22;color:#ffe7d8}
    @keyframes blink{0%,100%{box-shadow:0 0 0 0 rgba(33,150,243,0);}50%{box-shadow:0 0 0 4px rgba(33,150,243,.25);} }
    .blink{animation:blink 1.2s linear infinite;border-color:var(--primary) !important}
    .tile-rail{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
    .tile{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:12px;text-align:center}
    .tile .tcap{font-weight:700;font-size:12px}
    .btn-spread .btn{width:100%}
  </style>
</head>
<body>
<div class="page-wraper header-fixed">

  <!-- Header -->
  <header class="header">
    <div class="container">
      <div class="main-bar">
        <div class="left-content">
          <a href="crm_mobile.php" class="back-btn" aria-label="Back">
            <i class="fa-solid fa-arrow-left"></i>
          </a>
          <h4 class="title mb-0"><?php echo h($PAGE_TITLE); ?></h4>
        </div>
        <div class="mid-content"></div>
        <div class="right-content"></div>
      </div>
    </div>
  </header>
  <!-- Header End -->

  <!-- Page Content -->
  <div class="page-content">
    <div class="container crm-wrap">

      <?php if($pending){ ?>
        <div class="banner mb-3">You started a <strong><?php echo h(strtoupper($pending['type'])); ?></strong> with this contact. Please log the outcome.</div>
      <?php } ?>

      <!-- 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">ENQ<?php echo str_pad((string)$ID,6,'0',STR_PAD_LEFT); ?></div>
              <h5 class="crm-title mb-1"><?php echo h($VAL('name') ?: '—'); ?></h5>
              <div class="small">
                <?php if($F['created_at']): ?>
                  Created on: <?php echo h(date('d M Y', strtotime($rec[$F['created_at']]))); ?>
                <?php endif; ?>
                <?php if($VAL('badge')): ?>
                  &nbsp; • &nbsp;<span class="badge bg-secondary rounded-pill"><?php echo h($VAL('badge')); ?></span>
                <?php endif; ?>
                <?php if(strtolower($VAL('status'))==='dnd'): ?>
                  &nbsp; • &nbsp;<span class="text-danger fw-bold">DND</span>
                <?php endif; ?>
              </div>
            </div>
            <button class="btn btn-icon btn-rounded btn-secondary">
              <i class="fa-regular fa-star"></i>
            </button>
          </div>

          <div class="kv mt-3">
            <div class="k">Assigned to</div><div class="v"><?php echo h($VAL('assigned_to') ?: '—'); ?></div>
            <div class="k">Status</div><div class="v"><?php echo h($VAL('status') ?: '—'); ?></div>
            <div class="k">PP status</div><div class="v"><?php echo h($VAL('pp_status') ?: '—'); ?></div>
            <div class="k">Project</div><div class="v"><?php echo h($VAL('project') ?: '—'); ?></div>
          </div>
        </div>
      </div>

      <!-- External Quick Actions (use themed buttons/icons) -->
      <!--<div class="row g-2 btn-spread mb-3">
        <div class="col-6">
          <a href="</?php echo h($telHref); ?>" class="btn btn-phone btn-icon-text qa-out</?php echo $blinkCall; ?>" data-type="call">
            <i class="fa fa-phone"></i> Call
          </a>
        </div>
        <div class="col-6">
          <a href="</?php echo h($smsHref); ?>" class="btn btn-twitter btn-icon-text qa-out</?php echo $blinkSMS; ?>" data-type="sms">
            <i class="fa-solid fa-comment-sms"></i> SMS
          </a>
        </div>
        <div class="col-6">
          <a href="</?php echo h($waHref); ?>" target="_blank" class="btn btn-whatsapp btn-icon-text qa-out</?php echo $blinkWA; ?>" data-type="whatsapp">
            <i class="fab fa-whatsapp"></i> WhatsApp
          </a>
        </div>
        <div class="col-6">
          <a href="</?php echo h($mailHref); ?>" class="btn btn-email btn-icon-text qa-out</?php echo $blinkMail; ?>" data-type="mail">
            <i class="fa fa-envelope"></i> Email
          </a>
        </div>
      </div> -->

      <!-- In-page logger shortcuts (tiles) -->
      <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>
        <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>
        <button class="tile qa<?php echo $blinkTile['task']; ?>" data-action="task" title="Log Task">
          <div class="mb-1"><i class="fa-solid fa-clipboard-check"></i></div><div class="tcap">Task</div>
        </button>
        <button class="tile qa" data-action="meeting" title="Log Meeting">
          <div class="mb-1"><i class="fa-regular fa-calendar"></i></div><div class="tcap">Meeting</div>
        </button>
      </div>

      <!-- Member / PP tabs -->
      <ul class="nav nav-tabs mb-3" role="tablist">
        <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#pane-member" role="tab">Member</a></li>
        <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#pane-pp" role="tab">Property Pistol</a></li>
      </ul>

      <div class="tab-content">
        <div class="tab-pane fade show active" id="pane-member" role="tabpanel">
          <div class="card">
            <div class="card-body">
              <div class="mb-2"><div class="small">Assigned to</div><div class="fw-bold"><?php echo h($VAL('assigned_to') ?: '—'); ?></div></div>
              <div class="mb-2"><div class="small">Status</div><div class="fw-bold"><?php echo h($VAL('status') ?: '—'); ?></div></div>
              <div class="mb-2"><div class="small">Comment</div><div class="fw-bold"><?php echo h($VAL('comment') ?: '—'); ?></div></div>
              <div class="mb-2"><div class="small">Project</div><div class="fw-bold"><?php echo h($VAL('project') ?: '—'); ?></div></div>
              <a class="btn btn-primary w-100 mt-2" href="crm_edit.php?id=<?php echo (int)$ID; ?>">Edit</a>
            </div>
          </div>
        </div>
        <div class="tab-pane fade" id="pane-pp" role="tabpanel">
          <div class="card">
            <div class="card-body">
              <div class="small">No PP data configured.</div>
            </div>
          </div>
        </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>
  <!-- Page Content End -->

  <!-- Menubar (optional; keep if you use it elsewhere) -->
  <div class="menubar-area">
    <div class="toolbar-inner menubar-nav">
      <a href="index.html" class="nav-link">
        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="none"><path d="M21.44 11.035a.75.75 0 0 1-.69.465H18.5V19a2.25 2.25 0 0 1-2.25 2.25h-3a.75.75 0 0 1-.75-.75V16a.75.75 0 0 0-.75-.75h-1.5a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 1-.75.75h-3A2.25 2.25 0 0 1 3.5 19v-7.5H1.25a.75.75 0 0 1-.69-.465.75.75 0 0 1 .158-.818l9.75-9.75A.75.75 0 0 1 11 .246a.75.75 0 0 1 .533.222l9.75 9.75a.75.75 0 0 1 .158.818z" fill="#b5b5b5"/></svg>
      </a>
      <a href="timeline.html" class="nav-link">
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M11 19C15.4183 19 19 15.4183 19 11C19 6.58172 15.4183 3 11 3C6.58172 3 3 6.58172 3 11C3 15.4183 6.58172 19 11 19Z" stroke="#b5b5b5" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M21 21L16.65 16.65" stroke="#b5b5b5" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </a>
      <a href="create-post.html" class="nav-link add-post">
        <i class="fa-solid fa-plus"></i>
      </a>
      <a href="chat.html" class="nav-link">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="#b5b5b5" viewBox="0 0 511.606 511.606"><path d="M436.594 74.943c-99.917-99.917-261.637-99.932-361.568 0-80.348 80.347-95.531 199.817-48.029 294.96L.662 485.742c-3.423 15.056 10.071 28.556 25.133 25.133l115.839-26.335c168.429 84.092 369.846-37.653 369.846-228.812 0-68.29-26.595-132.494-74.886-180.785zM309.143 319.394h-160c-11.598 0-21-9.402-21-21s9.402-21 21-21h160c11.598 0 21 9.402 21 21s-9.402 21-21 21zm53.334-85.333H149.143c-11.598 0-21-9.402-21-21s9.402-21 21-21h213.334c11.598 0 21 9.402 21 21s-9.403 21-21 21z"/></svg>
      </a>
      <a href="profile.html" class="nav-link">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="21" fill="#b5b5b5"><path d="M8 7.75a3.75 3.75 0 1 0 0-7.5 3.75 3.75 0 1 0 0 7.5zm7.5 9v1.5c-.002.199-.079.39-.217.532C13.61 20.455 8.57 20.5 8 20.5s-5.61-.045-7.282-1.718C.579 18.64.501 18.449.5 18.25v-1.5a7.5 7.5 0 1 1 15 0z"/></svg>
      </a>
    </div>
  </div>
  <!-- Menubar End -->

</div>

<!-- Activity bottom-sheet / dialog -->
<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-primary 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>

<!-- Scripts -->
<script src="assets/js/jquery.js"></script>
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/settings.js"></script>
<script src="assets/js/custom.js"></script>
<script>
/* -------- Pending recorder for external actions (call/sms/wa/mail) -------- */
document.querySelectorAll('.qa-out').forEach(a=>{
  a.addEventListener('click', function(){
    const type=this.getAttribute('data-type');
    const payload='ajax=pending&eid=<?php echo (int)$ID; ?>&type='+encodeURIComponent(type);
    const url='crm_mobile.php?ajax=pending'; // same endpoint used on list page
    if(navigator.sendBeacon){
      const blob=new Blob([payload],{type:'application/x-www-form-urlencoded'});
      navigator.sendBeacon(url, blob);
    } else {
      fetch(url,{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:payload}).catch(()=>{});
    }
  }, {passive:true});
});

/* Logger sheet (Bootstrap Offcanvas) */
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');
  if(kind==='call'){ dir.value='Outbound'; } else { dir.value='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 pending and no recent activity */
<?php if($autoPromptType){ ?>
document.addEventListener('DOMContentLoaded', function(){
  actType = '<?php echo $autoPromptType; ?>';
  openSheet(actType);
});
<?php } ?>

/* Save activity */
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.text())
    .then(t=>{
      let j=null; try{ j=JSON.parse(t) }catch(e){}
      if(j&&j.ok){ alert('Activity saved'); location.reload(); }
      else { alert(j?(j.msg||'Failed'):('Failed')); console.log('RAW',t, j?.sql); }
    });
});
</script>
</body>
</html>
