<?php
require_once __DIR__.'/includes/functions.php';
$u=require_user(); verify_csrf(); mj_crm_ensure_schema();
$id=(int)($_GET['id']??$_POST['id']??0);
$c=one('SELECT c.*, co.name company_name FROM mj_customers c LEFT JOIN mj_companies co ON co.id=c.company_id WHERE c.id=? LIMIT 1',[$id]);
if(!$c || !mj_crm_customer_can_view($c,(int)$u['id'])){ $pageTitle='Customer not found'; include __DIR__.'/includes/header.php'; echo '<section class="mj-section"><div class="container"><div class="mj-card p-5 text-center"><h1 class="fw-bold">Customer not found</h1><p class="text-muted">This customer is not available.</p><a class="btn btn-primary" href="'.e(base_url('my-customers.php')).'">Back to Customers</a></div></div></section>'; include __DIR__.'/includes/footer.php'; exit; }

if($_SERVER['REQUEST_METHOD']==='POST'){
  $action=(string)($_POST['action']??'');
  try{
    if($action==='update_status'){
      $old=$c['status']; $new=(string)($_POST['status']??$old);
      q('UPDATE mj_customers SET status=?, tags=?, next_followup_at=?, private_note=?, updated_at=NOW() WHERE id=? AND owner_user_id=?',[
        $new,trim((string)($_POST['tags']??'')),trim((string)($_POST['next_followup_at']??''))?:null,trim((string)($_POST['private_note']??'')),$id,(int)$u['id']
      ]);
      mj_crm_timeline_add($id,'status','Status updated','Changed from '.mj_crm_status_label($old).' to '.mj_crm_status_label($new),'customer',$id,(int)$u['id']);
      flash('success','Customer updated.');
    } elseif($action==='add_note'){
      $note=trim((string)($_POST['note']??'')); if($note==='') throw new Exception('Please enter a note.');
      mj_crm_timeline_add($id,'note','Note added',$note,'customer',$id,(int)$u['id']);
      q('UPDATE mj_customers SET private_note=CONCAT(COALESCE(private_note,""), ?), updated_at=NOW() WHERE id=? AND owner_user_id=?',["\n".date('Y-m-d H:i').": ".$note,$id,(int)$u['id']]);
      flash('success','Note added.');
    }
  }catch(Throwable $e){ flash('error',$e->getMessage()); }
  redirect('customer-view.php?id='.$id);
}
$c=one('SELECT c.*, co.name company_name FROM mj_customers c LEFT JOIN mj_companies co ON co.id=c.company_id WHERE c.id=? LIMIT 1',[$id]);
$timeline=all_rows('SELECT * FROM mj_customer_timeline WHERE customer_id=? ORDER BY id DESC LIMIT 100',[$id]);
$quotes=table_exists('mj_quote_requests')?safe_all_rows_public('SELECT id,title,status,created_at FROM mj_quote_requests WHERE company_id<=>? AND (email=? OR customer_email=? OR user_id=?) ORDER BY id DESC LIMIT 20',[$c['company_id'],$c['email'],$c['email'],$c['customer_user_id']]):[];
$offers=table_exists('mj_offers')?safe_all_rows_public('SELECT o.id,o.status,o.amount,o.currency_code,l.title FROM mj_offers o LEFT JOIN mj_listings l ON l.id=o.listing_id WHERE o.seller_id=? AND o.buyer_id=? ORDER BY o.id DESC LIMIT 20',[$c['owner_user_id'],$c['customer_user_id']]):[];
$orders=table_exists('mj_orders')?safe_all_rows_public('SELECT id,order_number,status,total_amount,currency_code FROM mj_orders WHERE seller_id=? AND buyer_id=? ORDER BY id DESC LIMIT 20',[$c['owner_user_id'],$c['customer_user_id']]):[];
$pageTitle='Customer'; include __DIR__.'/includes/header.php';
?>
<div class="container py-5"><div class="sidebar-layout"><?php include __DIR__.'/includes/account-sidebar.php'; ?><section>
  <div class="mj-page-hero rounded-4 mb-4"><div class="container-fluid"><nav class="small mb-2"><a href="<?=e(base_url('my-customers.php'))?>">Customers</a> / <?=e($c['name'] ?: 'Customer #'.$id)?></nav><h1 class="fw-bold mb-1"><?=e($c['name'] ?: 'Customer #'.$id)?></h1><p class="text-muted mb-0"><?=e($c['company_name'] ?: 'General customer')?> · <?=e(mj_crm_status_label($c['status']))?></p></div></div>
  <?php show_flash(); ?>
  <div class="row g-4">
    <div class="col-lg-8">
      <div class="mj-card p-4 mb-4">
        <h4 class="fw-bold">Customer Timeline</h4>
        <?php if(!$timeline): ?><p class="text-muted">No timeline yet.</p><?php endif; ?>
        <?php foreach($timeline as $t): ?><div class="mj-timeline-item"><b><?=e($t['event_title'])?></b><p class="text-muted mb-1"><?=nl2br(e($t['event_note']))?></p><small><?=e($t['created_at'])?> · <?=e($t['event_type'])?></small></div><?php endforeach; ?>
      </div>

      <div class="mj-card p-4">
        <h4 class="fw-bold">Linked Activity</h4>
        <div class="row g-3">
          <div class="col-md-4"><h6 class="fw-bold">Quotes</h6><?php foreach($quotes as $q): ?><a class="d-block small" href="<?=e(base_url('quote-view.php?id='.(int)$q['id']))?>">#<?=e($q['id'])?> <?=e($q['title'] ?: 'Quote')?></a><?php endforeach; ?><?php if(!$quotes): ?><small class="text-muted">No quotes</small><?php endif; ?></div>
          <div class="col-md-4"><h6 class="fw-bold">Offers</h6><?php foreach($offers as $o): ?><a class="d-block small" href="<?=e(base_url('offer-view.php?id='.(int)$o['id']))?>">#<?=e($o['id'])?> <?=e($o['title'] ?: 'Offer')?></a><?php endforeach; ?><?php if(!$offers): ?><small class="text-muted">No offers</small><?php endif; ?></div>
          <div class="col-md-4"><h6 class="fw-bold">Enquiries</h6><?php foreach($orders as $o): ?><a class="d-block small" href="<?=e(base_url('order-view.php?id='.(int)$o['id']))?>"><?=e($o['order_number'] ?: '#'.$o['id'])?></a><?php endforeach; ?><?php if(!$orders): ?><small class="text-muted">No enquiries</small><?php endif; ?></div>
        </div>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="mj-card p-4 mb-4">
        <h4 class="fw-bold">Customer Profile</h4>
        <p class="mb-1"><b>Email:</b> <?=e($c['email'] ?: '-')?></p>
        <p class="mb-1"><b>Phone:</b> <?=e($c['phone'] ?: '-')?></p>
        <p class="mb-1"><b>WhatsApp:</b> <?=e($c['whatsapp'] ?: '-')?></p>
        <p class="mb-1"><b>Lead score:</b> <?=e($c['lead_score'])?>%</p>
        <p class="mb-3"><b>Source:</b> <?=e($c['source_type'])?> <?=e($c['source_label'])?></p>
        <div class="d-grid gap-2">
          <?php if($c['phone']): ?><a class="btn btn-outline-primary" href="tel:<?=e($c['phone'])?>"><i class="bi bi-telephone me-1"></i>Call</a><?php endif; ?>
          <?php if($c['whatsapp'] || $c['phone']): ?><a class="btn btn-outline-success" target="_blank" href="https://wa.me/<?=e(preg_replace('/\D+/','',$c['whatsapp'] ?: $c['phone']))?>"><i class="bi bi-whatsapp me-1"></i>WhatsApp</a><?php endif; ?>
          <?php if($c['email']): ?><a class="btn btn-outline-secondary" href="mailto:<?=e($c['email'])?>"><i class="bi bi-envelope me-1"></i>Email</a><?php endif; ?>
        </div>
      </div>

      <form method="post" class="mj-card p-4 mb-4">
        <?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><input type="hidden" name="action" value="update_status">
        <h4 class="fw-bold">Manage Customer</h4>
        <label class="form-label fw-bold">Status</label><select class="form-select mb-3" 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 class="form-label fw-bold">Tags</label><input class="form-control mb-3" name="tags" value="<?=e($c['tags'])?>" placeholder="VIP, urgent, follow-up">
        <label class="form-label fw-bold">Next follow-up</label><input class="form-control mb-3" 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 class="form-label fw-bold">Private note</label><textarea class="form-control mb-3" name="private_note" rows="4"><?=e($c['private_note'])?></textarea>
        <button class="btn btn-primary rounded-pill w-100">Save Customer</button>
      </form>

      <form method="post" class="mj-card p-4">
        <?=csrf_input()?><input type="hidden" name="id" value="<?=e($id)?>"><input type="hidden" name="action" value="add_note">
        <h4 class="fw-bold">Add Follow-up Note</h4>
        <textarea class="form-control mb-3" name="note" rows="3" placeholder="Called, WhatsApp sent, waiting for reply..."></textarea>
        <button class="btn btn-outline-primary rounded-pill w-100">Add Note</button>
      </form>
    </div>
  </div>
</section></div></div>
<?php include __DIR__.'/includes/footer.php'; ?>
