<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db = getDB();
$admin_page = 'leads';
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_lead'])) {
        $name = trim($_POST['name']);
        $company = trim($_POST['company']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $source = $_POST['source'];
        $notes = trim($_POST['notes']);
        $assigned = $_POST['assigned_to'] ? (int)$_POST['assigned_to'] : null;
        
        $db->prepare("INSERT INTO crm_leads (name,company,email,phone,source,notes,assigned_to) VALUES (?,?,?,?,?,?,?)")
           ->execute([$name,$company,$email,$phone,$source,$notes,$assigned]);
        $msg = 'Lead added successfully!';
    } elseif (isset($_POST['update_lead'])) {
        $id = (int)$_POST['lead_id'];
        $status = $_POST['status'];
        $assigned = $_POST['assigned_to'] ? (int)$_POST['assigned_to'] : null;
        $db->prepare("UPDATE crm_leads SET status=?, assigned_to=? WHERE id=?")->execute([$status, $assigned, $id]);
        $msg = 'Lead updated!';
    }
}

$leads = $db->query("SELECT l.*, e.name AS emp_name FROM crm_leads l LEFT JOIN employees e ON l.assigned_to=e.id ORDER BY l.created_at DESC")->fetchAll();
$employees = $db->query("SELECT id, name FROM employees WHERE status='active' AND role IN ('admin','sales_manager')")->fetchAll();

$page_title = 'CRM Leads';
include __DIR__ . '/header.php';
?>
<?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
  <h2>CRM Leads Pipeline</h2>
  <button onclick="document.getElementById('addLeadForm').style.display='block'" class="btn-primary">+ Add New Lead</button>
</div>

<div class="card" id="addLeadForm" style="display:none;margin-bottom:20px;">
  <div class="card-header"><h3>Add Manual Lead</h3></div>
  <div class="card-body">
    <form method="POST">
      <input type="hidden" name="add_lead" value="1">
      <div class="form-row">
        <div class="form-group"><label>Name *</label><input type="text" name="name" required></div>
        <div class="form-group"><label>Company</label><input type="text" name="company"></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label>Phone *</label><input type="text" name="phone" required></div>
        <div class="form-group"><label>Email</label><input type="email" name="email"></div>
      </div>
      <div class="form-row">
        <div class="form-group">
          <label>Source</label>
          <select name="source">
            <option value="website">Website</option>
            <option value="exhibition">Exhibition</option>
            <option value="referral">Referral</option>
            <option value="indiamart">IndiaMart / JustDial</option>
            <option value="cold_call">Cold Call</option>
          </select>
        </div>
        <div class="form-group">
          <label>Assign To</label>
          <select name="assigned_to">
            <option value="">-- Unassigned --</option>
            <?php foreach($employees as $e): ?><option value="<?= $e['id'] ?>"><?= h($e['name']) ?></option><?php endforeach; ?>
          </select>
        </div>
      </div>
      <div class="form-group"><label>Notes</label><textarea name="notes" rows="2"></textarea></div>
      <div style="display:flex;gap:10px;">
        <button type="submit" class="btn-primary">Save Lead</button>
        <button type="button" class="btn-action" onclick="document.getElementById('addLeadForm').style.display='none'">Cancel</button>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Lead Info</th>
          <th>Contact</th>
          <th>Source / Date</th>
          <th>Status</th>
          <th>Assigned To</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($leads as $l): ?>
        <tr>
          <td>
            <strong><?= h($l['name']) ?></strong><br>
            <span style="font-size:.8rem;color:var(--text-light);"><?= h($l['company']) ?></span>
          </td>
          <td>
            <a href="tel:<?= h($l['phone']) ?>"><?= h($l['phone']) ?></a><br>
            <a href="mailto:<?= h($l['email']) ?>" style="font-size:.8rem;"><?= h($l['email']) ?></a>
          </td>
          <td>
            <span style="font-size:.85rem;font-weight:600;color:var(--text-mid);"><?= ucfirst(str_replace('_',' ',$l['source'])) ?></span><br>
            <span style="font-size:.8rem;color:var(--text-light);"><?= date('d M Y', strtotime($l['created_at'])) ?></span>
          </td>
          <td>
            <form method="POST" id="form_<?= $l['id'] ?>" style="display:flex;flex-direction:column;gap:5px;">
              <input type="hidden" name="update_lead" value="1">
              <input type="hidden" name="lead_id" value="<?= $l['id'] ?>">
              <select name="status" onchange="document.getElementById('form_<?= $l['id'] ?>').submit()" style="padding:4px;font-size:.8rem;border-radius:4px;border:1px solid #e2e8f0;background:<?= $l['status']==='converted'?'#dcfce7':($l['status']==='lost'?'#fee2e2':'#f8fafc') ?>;">
                <?php foreach(['new','contacted','qualified','proposal_sent','converted','lost'] as $s): ?>
                <option value="<?= $s ?>" <?= $l['status']===$s?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
                <?php endforeach; ?>
              </select>
          </td>
          <td>
              <select name="assigned_to" onchange="document.getElementById('form_<?= $l['id'] ?>').submit()" style="padding:4px;font-size:.8rem;border-radius:4px;border:1px solid #e2e8f0;">
                <option value="">-- Unassigned --</option>
                <?php foreach($employees as $e): ?>
                <option value="<?= $e['id'] ?>" <?= $l['assigned_to']==$e['id']?'selected':'' ?>><?= h($e['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </form>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if(!$leads): ?>
        <tr><td colspan="5" style="text-align:center;">No leads found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>
