<?php
require_once 'config/db.php';

// Handle Add/Edit
$edit_id = null;
$edit_name = '';
$edit_desc = '';
$form_action = 'Add New';

if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM lead_funnels WHERE id = ?");
    $stmt->execute([$edit_id]);
    $item = $stmt->fetch();
    if ($item) {
        $edit_name = $item['name'];
        $edit_desc = $item['description'];
        $form_action = 'Edit';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_funnel'])) {
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);
    $id = isset($_POST['id']) && !empty($_POST['id']) ? (int)$_POST['id'] : null;

    if (!empty($name)) {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE lead_funnels SET name = ?, description = ? WHERE id = ?");
                $stmt->execute([$name, $desc, $id]);
                $success = "Funnel updated successfully.";
            } else {
                $stmt = $pdo->prepare("INSERT INTO lead_funnels (name, description) VALUES (?, ?)");
                $stmt->execute([$name, $desc]);
                $success = "Funnel added successfully.";
            }
            $edit_id = null;
            $edit_name = '';
            $edit_desc = '';
            $form_action = 'Add New';
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    } else {
        $error = "Funnel Name is required.";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM lead_funnels WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: lead_funnels.php?msg=deleted");
        exit;
    } catch (PDOException $e) {
        $error = "Cannot delete this funnel as it may be linked to specific leads and stages.";
    }
}

if (isset($_GET['msg']) && $_GET['msg'] === 'deleted') {
    $success = "Funnel deleted successfully.";
}

// Fetch list with stages count
$stmt = $pdo->query("
    SELECT f.*, COUNT(s.id) as stage_count 
    FROM lead_funnels f
    LEFT JOIN lead_stages s ON f.id = s.funnel_id
    GROUP BY f.id
    ORDER BY f.name ASC
");
$funnels = $stmt->fetchAll();

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-filter"></i> Lead Funnels</h2>
        <p>Manage your overarching sales pipelines and workflows.</p>
    </div>

    <?php if (isset($success)): ?>
        <div class="badge badge-completed" style="display:block; padding:15px; margin-bottom: 20px; font-size:1rem;"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?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; ?>

    <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 30px; align-items: start;">
        
        <!-- Add/Edit Form -->
        <div class="data-card" style="background:var(--white); padding:25px; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.03);">
            <h3 style="margin-bottom: 20px; color:var(--dark);"><?= $form_action ?> Funnel</h3>
            <form action="lead_funnels.php" method="POST">
                <input type="hidden" name="id" value="<?= htmlspecialchars((string)$edit_id) ?>">
                
                <div style="margin-bottom: 15px;">
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Funnel Name*</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($edit_name) ?>" required placeholder="e.g. Standard Construction" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>

                <div style="margin-bottom: 20px;">
                    <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Description</label>
                    <textarea name="description" rows="3" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit; resize:vertical;"><?= htmlspecialchars($edit_desc) ?></textarea>
                </div>
                
                <button type="submit" name="save_funnel" style="width:100%; padding:12px; background:var(--primary); color:var(--white); border:none; border-radius:6px; font-weight:600; cursor:pointer; transition:0.3s;">
                    <?= $form_action === 'Edit' ? 'Update Funnel' : 'Add Funnel' ?>
                </button>
                <?php if ($form_action === 'Edit'): ?>
                    <a href="lead_funnels.php" style="display:block; text-align:center; margin-top:10px; color:#64748b; text-decoration:none; font-size:0.9rem;">Cancel Edit</a>
                <?php endif; ?>
            </form>
        </div>

        <!-- List -->
        <div class="recent-activity" style="margin: 0;">
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="width: 80px;">S.No</th>
                            <th>Funnel Details</th>
                            <th style="width: 150px; text-align: right;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($funnels) > 0): ?>
                            <?php $sno = 1; foreach ($funnels as $f): ?>
                                <tr>
                                    <td style="color:#64748b; font-size:0.9rem;">#<?= $sno++ ?></td>
                                    <td>
                                        <div style="font-weight:600; color:var(--dark); margin-bottom:4px;"><?= htmlspecialchars($f['name']) ?></div>
                                        <div style="font-size:0.85rem; color:#64748b; margin-bottom:5px;"><?= htmlspecialchars($f['description'] ?: 'No description provided') ?></div>
                                        <div><span class="badge" style="background:#e0f2fe; color:var(--primary);"><i class="fa-solid fa-layer-group" style="margin-right:4px;"></i> <?= $f['stage_count'] ?> Stages inside</span></div>
                                    </td>
                                    <td style="text-align: right; vertical-align: middle;">
                                        <a href="lead_stages.php?funnel_id=<?= $f['id'] ?>" title="Manage Stages" style="color:var(--white); display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:var(--dark); border-radius:6px; margin-right:5px;"><i class="fa-solid fa-list-ol"></i></a>
                                        <a href="lead_funnels.php?edit=<?= $f['id'] ?>" style="color:var(--primary); display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:#e0f2fe; border-radius:6px; margin-right:5px;"><i class="fa-solid fa-pen"></i></a>
                                        <a href="lead_funnels.php?delete=<?= $f['id'] ?>" onclick="return confirm('Are you sure you want to delete this funnel completely?');" style="color:var(--danger); display:inline-flex; align-items:center; justify-content:center; width:32px; height:32px; background:#fee2e2; border-radius:6px;"><i class="fa-solid fa-trash"></i></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #94a3b8; padding: 20px;">No typical funnels found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<style>
@media (max-width: 768px) {
    .dashboard-content > div:not(.welcome-banner) {
        grid-template-columns: 1fr !important;
    }
}
</style>

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