<?php
require_once __DIR__.'/../includes/functions.php';
$admin=require_admin(); verify_csrf(); mj_crm_ensure_schema(); $adminTitle='Customer Profile';
$id=(int)($_GET['id']??$_POST['id']??0);
$c=one('SELECT c.*, co.name company_name, u.name owner_name, u.email owner_email FROM mj_customers c LEFT JOIN mj_companies co ON co.id=c.company_id LEFT JOIN mj_users u ON u.id=c.owner_user_id WHERE c.id=? LIMIT 1',[$id]);
if(!$c){ include __DIR__.'/_header.php'; echo '<div class="card"><div class="card-body text-center">Customer not found.</div></div>'; include __DIR__.'/_footer.php'; exit; }

if($_SERVER['REQUEST_METHOD']==='POST'){
  $action=(string)($_POST['action']??'');
  if($action==='update'){
    q('UPDATE mj_customers SET status=?, tags=?, next_followup_at=?, admin_note=?, is_blocked=?, updated_at=NOW() WHERE id=?',[
      (string)$_POST['status'], trim((string)$_POST['tags']), trim((string)$_POST['next_followup_at'])?:null, trim((string)$_POST['admin_note']), !empty($_POST['is_blocked'])?1:0, $id
    ]);
    mj_crm_timeline_add($id,'admin_update','Admin updated customer','Status/admin note updated','customer',$id,(int)$admin['id']);
    flash('success','Customer updated.');
  } elseif($action==='note'){
    $note=trim((string)($_POST['note']??'')); if($note!==''){ mj_crm_timeline_add($id,'admin_note','Admin note added',$note,'customer',$id,(int)$admin['id']); flash('success','Admin note added.');}
  }
  redirect('customer-view.php?id='.$id);
}
$timeline=all_rows('SELECT * FROM mj_customer_timeline WHERE customer_id=? ORDER BY id DESC LIMIT 150',[$id]);
include __DIR__.'/_header.php';
?>
<div class="card card-primary card-outline">
  <div class="card-header"><h3 class="card-title"><i class="fas fa-user mr-2"></i><?=e($c['name'] ?: 'Customer #'.$id)?></h3><div class="card-tools"><a href="customers.php" class="btn btn-sm btn-outline-secondary">Back</a></div></div>
  <div class="card-body"><?php show_flash(); ?>
    <div class="row">
      <div class="col-lg-4">
        <div class="card bg-light"><div class="card-body">
          <h5 class="font-weight-bold">Profile</h5>
          <p><b>Email:</b> <?=e($c['email'] ?: '-')?><br><b>Phone:</b> <?=e($c['phone'] ?: '-')?><br><b>WhatsApp:</b> <?=e($c['whatsapp'] ?: '-')?></p>
          <p><b>Owner:</b> <?=e($c['owner_name'] ?: $c['owner_email'])?><br><b>Company:</b> <?=e($c['company_name'] ?: 'General')?><br><b>Source:</b> <?=e($c['source_type'].' '.$c['source_label'])?></p>
          <p><b>Lead Score:</b> <?=e($c['lead_score'])?>%</p>
        </div></div>
        <form method="post" class="card"><div class="card-body">
          <?=csrf_input()?><input type="hidden" name="action" value="update"><input type="hidden" name="id" value="<?=e($id)?>">
          <label>Status</label><select class="form-control mb-2" name="status"><?php foreach(mj_crm_statuses() as $k=>$v): ?><option value="<?=e($k)?>" <?=$c['status']===$k?'selected':''?>><?=e($v)?></option><?php endforeach; ?></select>
          <label>Tags</label><input class="form-control mb-2" name="tags" value="<?=e($c['tags'])?>">
          <label>Next follow-up</label><input class="form-control mb-2" type="datetime-local" name="next_followup_at" value="<?=e($c['next_followup_at'] ? date('Y-m-d\TH:i',strtotime($c['next_followup_at'])) : '')?>">
          <label>Admin note</label><textarea class="form-control mb-2" name="admin_note" rows="4"><?=e($c['admin_note'])?></textarea>
          <div class="custom-control custom-switch mb-3"><input type="checkbox" class="custom-control-input" id="blocked" name="is_blocked" <?=!empty($c['is_blocked'])?'checked':''?>><label for="blocked" class="custom-control-label">Blocked / suspicious</label></div>
          <button class="btn btn-primary">Save</button>
        </div></form>
      </div>
      <div class="col-lg-8">
        <form method="post" class="card"><div class="card-body">
          <?=csrf_input()?><input type="hidden" name="action" value="note"><input type="hidden" name="id" value="<?=e($id)?>">
          <label>Add admin note</label><textarea class="form-control mb-2" name="note" rows="3"></textarea><button class="btn btn-outline-primary">Add Note</button>
        </div></form>
        <div class="card"><div class="card-body"><h5 class="font-weight-bold">Timeline</h5>
          <?php foreach($timeline as $t): ?><div class="border-left pl-3 mb-3"><b><?=e($t['event_title'])?></b><br><span class="text-muted"><?=nl2br(e($t['event_note']))?></span><br><small><?=e($t['created_at'])?> · <?=e($t['event_type'])?></small></div><?php endforeach; ?>
          <?php if(!$timeline): ?><p class="text-muted">No timeline found.</p><?php endif; ?>
        </div></div>
      </div>
    </div>
  </div>
</div>
<?php include __DIR__.'/_footer.php'; ?>
