<?php
require_once 'config/db.php';
function lead_add_edit_redirect($url) { header("Location: $url"); exit; }

$edit_id = isset($_GET['edit']) ? (int)$_GET['edit'] : null;

// Initialize form variables
$name = '';
$phone = '';
$email = '';
$project_type = '';
$source_id = '';
$status_id = '';
$notes = '';
$building_name = '';
$area = '';
$city = '';
$district = '';
$pincode = '';
$state = '';
$form_action = 'Add New';

// Fetch Master Data for dropdowns
$sources = $pdo->query("SELECT * FROM lead_sources ORDER BY name ASC")->fetchAll();
$statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name ASC")->fetchAll();
$project_types = $pdo->query("SELECT name FROM lead_services WHERE status='active' ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);

// Pre-load data if editing
if ($edit_id) {
    $stmt = $pdo->prepare("SELECT * FROM leads WHERE id = ?");
    $stmt->execute([$edit_id]);
    $lead = $stmt->fetch();
    
    if ($lead) {
        $name = $lead['name'];
        $phone = $lead['phone'];
        $email = $lead['email'];
        $project_type = $lead['project_type'] ?? '';
        $source_id = $lead['source_id'];
        $status_id = $lead['status_id'];
        $notes = $lead['notes'];
        $building_name = $lead['building_name'] ?? '';
        $area = $lead['area'] ?? '';
        $city = $lead['city'] ?? '';
        $district = $lead['district'] ?? '';
        $pincode = $lead['pincode'] ?? '';
        $state = $lead['state'] ?? '';
        $form_action = 'Edit';
    } else {
        lead_add_edit_redirect('leads.php');
    }
}

$enquiry_id = isset($_GET['enquiry_id']) ? (int)$_GET['enquiry_id'] : null;
if ($enquiry_id) {
    $stmt = $pdo->prepare("SELECT * FROM enquiries WHERE id = ?");
    $stmt->execute([$enquiry_id]);
    $enq = $stmt->fetch();
    
    if ($enq) {
        $name = $enq['full_name'];
        $phone = $enq['phone'];
        $email = $enq['email'];
        $project_type = $enq['interest'] ?? ''; // Try to map interest to project type
        $notes = "Original Enquiry Interest: " . $enq['interest'] . "\n\nClient Message:\n" . $enq['message'];
        $form_action = 'Convert Enquiry to';
    } else {
        lead_add_edit_redirect('enquiries.php');
    }
}

// Handle Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $enquiry_id_post = !empty($_POST['enquiry_id']) ? (int)$_POST['enquiry_id'] : null;
    $name = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $project_type = trim($_POST['project_type'] ?? '');
    $source_id = !empty($_POST['source_id']) ? (int)$_POST['source_id'] : null;
    $status_id = !empty($_POST['status_id']) ? (int)$_POST['status_id'] : null;
    $notes = trim($_POST['notes'] ?? '');
    $building_name = trim($_POST['building_name'] ?? '');
    $area = trim($_POST['area'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $district = trim($_POST['district'] ?? '');
    $pincode = trim($_POST['pincode'] ?? '');
    $state = trim($_POST['state'] ?? '');

    if (empty($name) || empty($phone)) {
        $error = "Name and Phone are mandatory fields.";
    } else {
        try {
            if ($edit_id) {
                $stmt = $pdo->prepare("UPDATE leads SET name=?, phone=?, email=?, building_name=?, area=?, city=?, district=?, pincode=?, state=?, project_type=?, source_id=?, status_id=?, notes=? WHERE id=?");
                $stmt->execute([$name, $phone, $email, $building_name, $area, $city, $district, $pincode, $state, $project_type, $source_id, $status_id, $notes, $edit_id]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO leads (name, phone, email, building_name, area, city, district, pincode, state, project_type, source_id, status_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $phone, $email, $building_name, $area, $city, $district, $pincode, $state, $project_type, $source_id, $status_id, $notes]);
                
                if ($enquiry_id_post) {
                    $pdo->prepare("UPDATE enquiries SET status = 'converted' WHERE id = ?")->execute([$enquiry_id_post]);
                }
            }
            lead_add_edit_redirect('leads.php');
        } catch (PDOException $e) {
            $error = "Database Error: " . $e->getMessage();
        }
    }
}

require_once 'includes/header.php';
?>

<!-- International Phone Input CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/css/intlTelInput.css">
<style>
    .iti { width: 100%; }
    .iti__flag-container { border-radius: 6px 0 0 6px; }
</style>

<div class="dashboard-content" style="max-width: 750px; margin: 0 auto;">
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 25px;">
        <h2><?= $form_action ?> Lead</h2>
        <a href="leads.php" style="color:var(--text-main); text-decoration: none; font-weight: 500;"><i class="fa-solid fa-arrow-left"></i> Back to Leads</a>
    </div>

    <?php if (isset($error)): ?>
        <div class="badge badge-pending" style="display:block; padding:15px; margin-bottom: 20px; background-color: #fee2e2; color: #ef4444; font-size:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form action="" method="POST" class="data-card" style="background:#fff; padding:30px; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
        
        <?php if($enquiry_id): ?>
            <input type="hidden" name="enquiry_id" value="<?= htmlspecialchars((string)$enquiry_id) ?>">
            <div style="background:#d1fae5; color:#065f46; margin-bottom: 20px; display:inline-block; padding:10px 15px; border-radius:6px; font-weight:600; font-size:0.9rem;">
                <i class="fa-solid fa-arrow-right-arrow-left" style="margin-right:5px;"></i> Converting an enquiry into a lead. The original enquiry will be marked as converted.
            </div>
        <?php endif; ?>

        <h4 style="margin-bottom:20px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px;">
            <i class="fa-solid fa-address-card"></i> Contact Information
        </h4>
        <div class="form-grid">
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Full Name *</label>
                <input type="text" name="name" value="<?= htmlspecialchars($name) ?>" required style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Phone Number *</label>
                <input type="tel" name="phone" id="phone" value="<?= htmlspecialchars($phone) ?>" required style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Email Address</label>
                <input type="email" name="email" value="<?= htmlspecialchars($email ?? '') ?>" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
        </div>
        
        <div class="form-grid">
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Project Type</label>
                <select name="project_type" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">-- Select Project Type --</option>
                    <?php foreach ($project_types as $pt): ?>
                        <option value="<?= $pt ?>" <?= $project_type === $pt ? 'selected' : '' ?>><?= $pt ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Building Name / Door No</label>
                <input type="text" name="building_name" value="<?= htmlspecialchars($building_name) ?>" placeholder="e.g. #12, Sunshine Apts" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Area / Street Name</label>
                <input type="text" name="area" value="<?= htmlspecialchars($area) ?>" placeholder="e.g. 3rd Cross, MG Road" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">City</label>
                <input type="text" name="city" value="<?= htmlspecialchars($city) ?>" placeholder="e.g. Krishnagiri" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">District</label>
                <input type="text" name="district" value="<?= htmlspecialchars($district) ?>" placeholder="e.g. Krishnagiri" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Pincode</label>
                <input type="text" name="pincode" value="<?= htmlspecialchars($pincode) ?>" placeholder="e.g. 635001" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">State</label>
                <input type="text" name="state" value="<?= htmlspecialchars($state) ?>" placeholder="e.g. Tamil Nadu" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px;">
            </div>
        </div>

        <h4 style="margin-bottom:20px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px;">
            <i class="fa-solid fa-diagram-project"></i> Pipeline Information
        </h4>
        <div class="form-grid">
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Lead Source</label>
                <select name="source_id" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">-- Select Source --</option>
                    <?php foreach ($sources as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $source_id == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Pipeline Status</label>
                <select name="status_id" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px; background:#fff;">
                    <option value="">-- Select Status --</option>
                    <?php foreach ($statuses as $st): ?>
                        <option value="<?= $st['id'] ?>" <?= $status_id == $st['id'] ? 'selected' : '' ?>><?= htmlspecialchars($st['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>

        <h4 style="margin-bottom:15px; color:var(--primary); border-bottom:1px solid var(--border); padding-bottom:10px;">
            <i class="fa-solid fa-note-sticky"></i> Notes
        </h4>
        <div style="margin-bottom:30px;">
            <textarea name="notes" rows="4" style="width:100%; padding:12px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"><?= htmlspecialchars($notes) ?></textarea>
        </div>

        <div style="border-top:1px solid var(--border); padding-top:20px; display:flex; justify-content:flex-end; gap:10px;">
            <a href="leads.php" style="padding:12px 25px; background:#e2e8f0; color:var(--dark); border-radius:6px; text-decoration:none; font-weight:600;">Cancel</a>
            <button type="submit" style="padding:12px 30px; background:var(--primary); color:var(--white); border:none; border-radius:6px; font-weight:600; cursor:pointer;"><i class="fa-solid fa-save"></i> Save Lead</button>
        </div>
    </form>
</div>

<style>
.form-grid { display:grid; grid-template-columns:1fr 1fr; gap:20px; margin-bottom:25px; }
@media (max-width: 600px) {
    .form-grid { grid-template-columns: 1fr !important; gap: 15px; }
    .dashboard-content { padding: 15px; }
    form { padding: 20px !important; }
}
</style>

<?php require_once 'includes/footer.php'; ?>

<!-- International Phone Input JS -->
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/intlTelInput.min.js"></script>
<script>
    const phoneInput = document.querySelector("#phone");
    const iti = window.intlTelInput(phoneInput, {
        initialCountry: "in",
        separateDialCode: true,
        utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/utils.js",
    });

    // Ensure we submit the full number with dial code if needed, 
    // but for simplicity here we just let it be. 
    // If the user wants the dial code saved, we should sync it to a hidden field.
    // However, the phone field usually expects the full number.
</script>
