<?php
$active = 'leads';
$pageTitle = 'Leads';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$action = $_GET['action'] ?? '';
$id = (int)($_GET['id'] ?? 0);
$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $mode = $_POST['mode'] ?? '';
  if ($mode === 'save') {
    $lead_id = (int)($_POST['lead_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $customer_name = trim($_POST['customer_name'] ?? '');
    $customer_phone = trim($_POST['customer_phone'] ?? '');
    $service_details = trim($_POST['service_details'] ?? '');
    $time_slot = trim($_POST['time_slot'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $lead_price = (int)($_POST['lead_price'] ?? 0);
    $is_available = isset($_POST['is_available']) ? 1 : 0;
    $category_id = !empty($_POST['category_id']) ? (int)$_POST['category_id'] : null;
    $payment_mode = in_array($_POST['payment_mode'] ?? '', ['online','cod']) ? $_POST['payment_mode'] : 'online';

    if ($title===''||$customer_name===''||$time_slot===''||$location===''||$lead_price<=0) {
      $msg = "<div class='alert alert-danger'>Title, customer, time_slot, location, lead_price are required.</div>";
    } else {
      if ($lead_id) {
        $stmt = $pdo->prepare("UPDATE leads SET title=?, customer_name=?, customer_phone=?, service_details=?, time_slot=?, location=?, lead_price=?, is_available=?, category_id=?, payment_mode=? WHERE id=?");
        $stmt->execute([$title,$customer_name,$customer_phone,$service_details,$time_slot,$location,$lead_price,$is_available,$category_id,$payment_mode,$lead_id]);
        $msg = "<div class='alert alert-success'>Lead updated.</div>";
      } else {
        $stmt = $pdo->prepare("INSERT INTO leads (title, customer_name, customer_phone, service_details, time_slot, location, lead_price, is_available, category_id, payment_mode) VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$title,$customer_name,$customer_phone,$service_details,$time_slot,$location,$lead_price,$is_available,$category_id,$payment_mode]);
        $msg = "<div class='alert alert-success'>Lead created.</div>";
      }
      $action = '';
      $id = 0;
    }
  }

  if ($mode === 'toggle') {
    $lead_id = (int)($_POST['lead_id'] ?? 0);
    $stmt = $pdo->prepare("UPDATE leads SET is_available = IF(is_available=1,0,1) WHERE id=?");
    $stmt->execute([$lead_id]);
    $msg = "<div class='alert alert-success'>Lead availability toggled.</div>";
  }
}

if ($action === 'edit' || $action === 'add') {
  $categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
  $lead = [
    'id'=>0,'title'=>'','customer_name'=>'','customer_phone'=>'','service_details'=>'',
    'time_slot'=>'','location'=>'','lead_price'=>100,'is_available'=>1,'category_id'=>null,'payment_mode'=>'online'
  ];
  if ($action === 'edit') {
    $stmt = $pdo->prepare("SELECT * FROM leads WHERE id=?");
    $stmt->execute([$id]);
    $lead = $stmt->fetch();
    if (!$lead) { echo "<div class='alert alert-danger'>Lead not found</div>"; require_once __DIR__.'/partials/bottom.php'; exit; }
  }
  ?>
  <div class="d-flex justify-content-between align-items-center mb-3">
    <div>
      <h4 class="fw-bold mb-0"><?php echo $action==='add'?'Create Lead':'Edit Lead'; ?></h4>
      <div class="text-muted small">Leads are visible in the vendor app when available.</div>
    </div>
    <a class="btn btn-outline-dark" href="leads.php">Back</a>
  </div>

  <?php echo $msg; ?>

  <div class="card p-4">
    <form method="post">
      <input type="hidden" name="mode" value="save">
      <input type="hidden" name="lead_id" value="<?php echo (int)$lead['id']; ?>">
      <div class="row g-3">
        <div class="col-md-8">
          <label class="form-label">Title</label>
          <input class="form-control" name="title" required value="<?php echo htmlspecialchars($lead['title']); ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Lead Price (₹)</label>
          <input class="form-control" type="number" min="1" name="lead_price" required value="<?php echo (int)$lead['lead_price']; ?>">
        </div>

        <div class="col-md-6">
          <label class="form-label">Customer Name</label>
          <input class="form-control" name="customer_name" required value="<?php echo htmlspecialchars($lead['customer_name']); ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Customer Phone</label>
          <input class="form-control" name="customer_phone" value="<?php echo htmlspecialchars($lead['customer_phone'] ?? ''); ?>">
        </div>

        <div class="col-12">
          <label class="form-label">Service Details</label>
          <textarea class="form-control" name="service_details" rows="3"><?php echo htmlspecialchars($lead['service_details'] ?? ''); ?></textarea>
        </div>

        <div class="col-md-6">
          <label class="form-label">Time Slot</label>
          <input class="form-control" name="time_slot" placeholder="e.g., Today 10:00-12:00" required value="<?php echo htmlspecialchars($lead['time_slot']); ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Location</label>
          <input class="form-control" name="location" required value="<?php echo htmlspecialchars($lead['location']); ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">Category</label>
          <select class="form-select" name="category_id">
            <option value="">— Select Category —</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo ((int)($lead['category_id']??0))===(int)$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
            <?php endforeach; ?>
          </select>
          <div class="form-text">From categories master</div>
        </div>
        <div class="col-md-4">
          <label class="form-label">Payment Mode</label>
          <select class="form-select" name="payment_mode">
            <option value="online" <?php echo ($lead['payment_mode']??'online')==='online'?'selected':''; ?>>Online</option>
            <option value="cod" <?php echo ($lead['payment_mode']??'')==='cod'?'selected':''; ?>>Cash on Delivery (COD)</option>
          </select>
        </div>

        <div class="col-12">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" name="is_available" id="avail" <?php if ((int)$lead['is_available']===1) echo 'checked'; ?>>
            <label class="form-check-label" for="avail">Available in Vendor App</label>
          </div>
        </div>

        <div class="col-12 d-flex gap-2">
          <button class="btn btn-dark" type="submit">Save Lead</button>
        </div>
      </div>
    </form>
  </div>
  <?php
  require_once __DIR__ . '/partials/bottom.php';
  exit;
}

$leads = $pdo->query("SELECT l.*, c.name AS category_name FROM leads l LEFT JOIN categories c ON c.id=l.category_id ORDER BY l.created_at DESC")->fetchAll();
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="fw-bold mb-0">Leads</h4>
    <div class="text-muted small">Create, edit, and enable/disable leads.</div>
  </div>
  <a class="btn btn-dark" href="leads.php?action=add">+ Create Lead</a>
</div>

<?php echo $msg; ?>

<div class="card p-3">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead>
        <tr>
          <th>Title</th>
          <th>Customer</th>
          <th>Category</th>
          <th>Payment</th>
          <th>Time Slot</th>
          <th>Location</th>
          <th>Price</th>
          <th>Status</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($leads as $l): ?>
          <tr>
            <td class="fw-semibold"><?php echo htmlspecialchars($l['title']); ?></td>
            <td><?php echo htmlspecialchars($l['customer_name']); ?></td>
            <td class="small"><?php echo htmlspecialchars($l['category_name'] ?? '—'); ?></td>
            <td><span class="badge bg-<?php echo ($l['payment_mode']??'online')==='cod'?'warning':'primary'; ?>"><?php echo $l['payment_mode'] ?? 'online'; ?></span></td>
            <td><?php echo htmlspecialchars($l['time_slot']); ?></td>
            <td><?php echo htmlspecialchars($l['location']); ?></td>
            <td>₹<?php echo (int)$l['lead_price']; ?></td>
            <td>
              <?php if ((int)$l['is_available']===1): ?>
                <span class="badge text-bg-success">available</span>
              <?php else: ?>
                <span class="badge text-bg-secondary">disabled</span>
              <?php endif; ?>
            </td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-dark" href="leads.php?action=edit&id=<?php echo (int)$l['id']; ?>">Edit</a>
              <form method="post" style="display:inline;">
                <input type="hidden" name="mode" value="toggle">
                <input type="hidden" name="lead_id" value="<?php echo (int)$l['id']; ?>">
                <button class="btn btn-sm btn-dark" type="submit"><?php echo (int)$l['is_available']===1?'Disable':'Enable'; ?></button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (count($leads)===0): ?>
          <tr><td colspan="9" class="text-muted">No leads found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . '/partials/bottom.php'; ?>
