<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$lead_id = $_GET['id'] ?? null;
$lead = null;
$is_edit = false;

if ($lead_id) {
    $is_edit = true;
    $sql = "SELECT * FROM leads WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $lead_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $lead = $result->fetch_assoc();
    
    if (!$lead) {
        header('Location: list_leads.php');
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $interest_type = $_POST['interest_type'] ?? 'Rent';
    $property_interested_in = $_POST['property_interested_in'] ?? null;
    $budget_min = $_POST['budget_min'] ?? null;
    $budget_max = $_POST['budget_max'] ?? null;
    $preferred_location = trim($_POST['preferred_location'] ?? '');
    $source = trim($_POST['source'] ?? '');
    $status = $_POST['status'] ?? 'New';
    $assigned_agent_id = $_POST['assigned_agent_id'] ?? null;
    $notes = trim($_POST['notes'] ?? '');
    
    if ($is_edit) {
        $sql = "UPDATE leads SET first_name = ?, last_name = ?, email = ?, phone = ?, 
                interest_type = ?, property_interested_in = ?, budget_min = ?, budget_max = ?, 
                preferred_location = ?, source = ?, status = ?, assigned_agent_id = ?, notes = ?
                WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssiddsssisi", $first_name, $last_name, $email, $phone, 
                         $interest_type, $property_interested_in, $budget_min, $budget_max, 
                         $preferred_location, $source, $status, $assigned_agent_id, $notes, $lead_id);
        $success_message = "Lead updated successfully!";
    } else {
        $sql = "INSERT INTO leads (first_name, last_name, email, phone, interest_type, 
                                   property_interested_in, budget_min, budget_max, preferred_location, 
                                   source, status, assigned_agent_id, notes, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssiddssssi", $first_name, $last_name, $email, $phone, 
                         $interest_type, $property_interested_in, $budget_min, $budget_max, 
                         $preferred_location, $source, $status, $assigned_agent_id, $notes);
        $success_message = "Lead added successfully!";
    }
    
    if ($stmt->execute()) {
        $_SESSION['success_message'] = $success_message;
        header('Location: list_leads.php');
        exit();
    } else {
        $error_message = "Error: " . $conn->error;
    }
}

// Get properties
$sql_properties = "SELECT * FROM properties ORDER BY name";
$result_properties = $conn->query($sql_properties);

// Get agents
$sql_agents = "SELECT u.* FROM users u 
               JOIN roles r ON u.role_id = r.id 
               WHERE r.role_name IN ('Property Agent', 'Super Admin')
               ORDER BY u.first_name, u.last_name";
$result_agents = $conn->query($sql_agents);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($is_edit ? 'Edit' : 'Add') . ' Lead')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array(
                        'pagetitle' => 'CRM', 
                        'title' => ($is_edit ? 'Edit' : 'Add') . ' Lead'
                    )); ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <?php echo $is_edit ? 'Edit Lead' : 'Add New Lead'; ?>
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <?php if (isset($error_message)): ?>
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                            <?php echo htmlspecialchars($error_message); ?>
                                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                        </div>
                                    <?php endif; ?>

                                    <form method="POST" id="leadForm">
                                        <h5 class="mb-3">Contact Information</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">First Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="first_name" 
                                                       value="<?php echo htmlspecialchars($lead['first_name'] ?? ''); ?>" 
                                                       required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="last_name" 
                                                       value="<?php echo htmlspecialchars($lead['last_name'] ?? ''); ?>" 
                                                       required>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" 
                                                       value="<?php echo htmlspecialchars($lead['email'] ?? ''); ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Phone <span class="text-danger">*</span></label>
                                                <input type="tel" class="form-control" name="phone" 
                                                       value="<?php echo htmlspecialchars($lead['phone'] ?? ''); ?>" 
                                                       required>
                                            </div>
                                        </div>

                                        <h5 class="mb-3 mt-4">Interest Details</h5>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Interest Type <span class="text-danger">*</span></label>
                                                <select class="form-select" name="interest_type" required>
                                                    <option value="Rent" <?php echo ($lead['interest_type'] ?? 'Rent') == 'Rent' ? 'selected' : ''; ?>>Rent</option>
                                                    <option value="Buy" <?php echo ($lead['interest_type'] ?? '') == 'Buy' ? 'selected' : ''; ?>>Buy</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Property Interested In</label>
                                                <select class="form-select" name="property_interested_in">
                                                    <option value="">Select Property (Optional)</option>
                                                    <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                        <option value="<?php echo $prop['id']; ?>" 
                                                                <?php echo (($lead['property_interested_in'] ?? '') == $prop['id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($prop['name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Budget Min (KES)</label>
                                                <input type="number" class="form-control" name="budget_min" 
                                                       value="<?php echo $lead['budget_min'] ?? ''; ?>" 
                                                       step="0.01">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Budget Max (KES)</label>
                                                <input type="number" class="form-control" name="budget_max" 
                                                       value="<?php echo $lead['budget_max'] ?? ''; ?>" 
                                                       step="0.01">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Preferred Location</label>
                                                <input type="text" class="form-control" name="preferred_location" 
                                                       value="<?php echo htmlspecialchars($lead['preferred_location'] ?? ''); ?>" 
                                                       placeholder="e.g., Kilimani">
                                            </div>
                                        </div>

                                        <h5 class="mb-3 mt-4">Lead Management</h5>
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Status</label>
                                                <select class="form-select" name="status">
                                                    <option value="New" <?php echo ($lead['status'] ?? 'New') == 'New' ? 'selected' : ''; ?>>New</option>
                                                    <option value="Contacted" <?php echo ($lead['status'] ?? '') == 'Contacted' ? 'selected' : ''; ?>>Contacted</option>
                                                    <option value="Viewing Scheduled" <?php echo ($lead['status'] ?? '') == 'Viewing Scheduled' ? 'selected' : ''; ?>>Viewing Scheduled</option>
                                                    <option value="Offer Made" <?php echo ($lead['status'] ?? '') == 'Offer Made' ? 'selected' : ''; ?>>Offer Made</option>
                                                    <option value="Converted" <?php echo ($lead['status'] ?? '') == 'Converted' ? 'selected' : ''; ?>>Converted</option>
                                                    <option value="Lost" <?php echo ($lead['status'] ?? '') == 'Lost' ? 'selected' : ''; ?>>Lost</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Assigned Agent</label>
                                                <select class="form-select" name="assigned_agent_id">
                                                    <option value="">Unassigned</option>
                                                    <?php while($agent = $result_agents->fetch_assoc()): ?>
                                                        <option value="<?php echo $agent['id']; ?>" 
                                                                <?php echo (($lead['assigned_agent_id'] ?? '') == $agent['id']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($agent['first_name'] . ' ' . $agent['last_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Source</label>
                                                <input type="text" class="form-control" name="source" 
                                                       value="<?php echo htmlspecialchars($lead['source'] ?? ''); ?>" 
                                                       placeholder="e.g., Website, Facebook, Walk-in">
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Notes</label>
                                            <textarea class="form-control" name="notes" rows="4" 
                                                      placeholder="Additional notes about this lead..."><?php echo htmlspecialchars($lead['notes'] ?? ''); ?></textarea>
                                        </div>

                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line align-bottom me-1"></i>
                                                <?php echo $is_edit ? 'Update Lead' : 'Add Lead'; ?>
                                            </button>
                                            <a href="list_leads.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i>Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
