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

// Fetch all available funnels and statuses for the dropdowns
$stmtFunnels = $pdo->query("SELECT * FROM lead_funnels ORDER BY name ASC");
$all_funnels = $stmtFunnels->fetchAll();

$stmtStatuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name ASC");
$all_statuses = $stmtStatuses->fetchAll();

// Get the currently selected funnel (optional)
$active_funnel_id = isset($_GET['funnel_id']) && !empty($_GET['funnel_id']) ? (int)$_GET['funnel_id'] : null;

// Handle Add/Edit
$edit_id = null;
$edit_name = '';
$edit_order = '0';
$edit_status_id = null;
$form_action = 'Add New';

if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM lead_stages WHERE id = ?");
    $stmt->execute([$edit_id]);
    $item = $stmt->fetch();
    if ($item) {
        $edit_name = $item['name'];
        $edit_order = $item['stage_order'];
        $edit_status_id = $item['status_id'];
        $active_funnel_id = $item['funnel_id'];
        $form_action = 'Edit';
    }
}

// Ensure there is at least a selected funnel ID for submitting the form correctly if we are not editing
if (!$active_funnel_id && count($all_funnels) > 0) {
    $active_funnel_id = $all_funnels[0]['id'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_stage'])) {
    $name = trim($_POST['name']);
    $funnel_id = (int)$_POST['funnel_id'];
    $order = (int)$_POST['stage_order'];
    $status_id = !empty($_POST['status_id']) ? (int)$_POST['status_id'] : null;
    $id = isset($_POST['id']) && !empty($_POST['id']) ? (int)$_POST['id'] : null;

    if (!empty($name) && $funnel_id > 0) {
        try {
            if ($id) {
                $stmt = $pdo->prepare("UPDATE lead_stages SET funnel_id = ?, name = ?, stage_order = ?, status_id = ? WHERE id = ?");
                $stmt->execute([$funnel_id, $name, $order, $status_id, $id]);
                $success = "Stage updated successfully.";
            } else {
                $stmt = $pdo->prepare("INSERT INTO lead_stages (funnel_id, name, stage_order, status_id) VALUES (?, ?, ?, ?)");
                $stmt->execute([$funnel_id, $name, $order, $status_id]);
                $success = "Stage added successfully.";
            }
            $active_funnel_id = $funnel_id;
            $edit_id = null;
            $edit_name = '';
            $edit_order = '0';
            $edit_status_id = null;
            $form_action = 'Add New';
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    } else {
        $error = "Stage Name and Funnel choice are required.";
    }
}

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $funnel_id_to_return = isset($_GET['f_id']) ? (int)$_GET['f_id'] : '';
    try {
        $stmt = $pdo->prepare("DELETE FROM lead_stages WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: lead_stages.php?funnel_id=$funnel_id_to_return&msg=deleted");
        exit;
    } catch (PDOException $e) {
        $error = "Cannot delete this stage, it likely has active leads assigned to it.";
    }
}

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

// Fetch list for the active funnel, joining to get status info
$stages = [];
if ($active_funnel_id) {
    $stmt = $pdo->prepare("
        SELECT ls.*, lstat.name as status_name, lstat.color_code as status_color
        FROM lead_stages ls
        LEFT JOIN lead_statuses lstat ON ls.status_id = lstat.id
        WHERE ls.funnel_id = ? 
        ORDER BY ls.stage_order ASC, ls.name ASC
    ");
    $stmt->execute([$active_funnel_id]);
    $stages = $stmt->fetchAll();
}

require_once 'includes/header.php';
?>

<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px; display:flex; justify-content:space-between; align-items:center;">
        <div>
            <h2><i class="fa-solid fa-list-ol"></i> Lead Stages</h2>
            <p>Define the chronological checkpoints for your active funnels.</p>
        </div>
        
        <div>
            <!-- Funnel Selector -->
            <form action="lead_stages.php" method="GET" style="display: flex; align-items: center; gap: 10px;">
                <label style="font-weight: 600; color: rgba(255,255,255,0.8);">Viewing Funnel:</label>
                <select name="funnel_id" onchange="this.form.submit()" style="padding: 10px; border-radius: 6px; border: none; font-weight: 600; min-width: 200px;">
                    <?php if (count($all_funnels) === 0): ?>
                        <option value="">No funnels available</option>
                    <?php else: ?>
                        <?php foreach ($all_funnels as $f): ?>
                            <option value="<?= $f['id'] ?>" <?= $f['id'] == $active_funnel_id ? 'selected' : '' ?>><?= htmlspecialchars($f['name']) ?></option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
            </form>
        </div>
    </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 ?> Stage</h3>
            
            <?php if(count($all_funnels) === 0): ?>
                <div style="color:var(--danger); font-size: 0.9rem; padding: 15px; background: #fee2e2; border-radius: 6px;">You must create a Funnel first before adding stages.</div>
            <?php else: ?>
                <form action="lead_stages.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;">Assign to Funnel</label>
                        <select name="funnel_id" required style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                            <?php foreach ($all_funnels as $f): ?>
                                <option value="<?= $f['id'] ?>" <?= $f['id'] == $active_funnel_id ? 'selected' : '' ?>><?= htmlspecialchars($f['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Stage Name*</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($edit_name) ?>" required placeholder="e.g. Quotation Sent" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                    </div>

                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Stage Order (Position)</label>
                        <input type="number" name="stage_order" value="<?= htmlspecialchars($edit_order) ?>" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                        <span style="font-size: 0.8rem; color:#64748b; margin-top:5px; display:block;">Lower numbers show up first (e.g. 10, 20, 30).</span>
                    </div>

                    <div style="margin-bottom: 20px;">
                        <label style="display:block; margin-bottom:8px; font-weight:600; font-size:0.9rem;">Maps to Lead Status <span style="color:#94a3b8; font-weight:400;">(optional)</span></label>
                        <select name="status_id" style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                            <option value="">-- None (no auto status) --</option>
                            <?php foreach ($all_statuses as $st): ?>
                                <option value="<?= $st['id'] ?>" <?= $st['id'] == $edit_status_id ? 'selected' : '' ?>><?= htmlspecialchars($st['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <span style="font-size: 0.8rem; color:#64748b; margin-top:5px; display:block;">When a lead moves to this stage, their status can be set automatically.</span>
                    </div>
                    
                    <button type="submit" name="save_stage" 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 Stage' : 'Add Stage' ?>
                    </button>
                    
                    <?php if ($form_action === 'Edit'): ?>
                        <a href="lead_stages.php?funnel_id=<?= $active_funnel_id ?>" style="display:block; text-align:center; margin-top:10px; color:#64748b; text-decoration:none; font-size:0.9rem;">Cancel Edit</a>
                    <?php endif; ?>
                </form>
            <?php endif; ?>
        </div>

        <!-- List -->
        <div class="recent-activity" style="margin: 0;">
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th style="width: 60px;">Order</th>
                            <th>Stage Name</th>
                            <th>Mapped Status</th>
                            <th style="width: 100px; text-align: right;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($stages) > 0): ?>
                            <?php foreach ($stages as $stage): ?>
                                <tr>
                                    <td style="color:var(--dark); font-weight:700;">
                                        <div style="background: #f1f5f9; width: 35px; height: 35px; display:flex; align-items:center; justify-content:center; border-radius:6px; border:1px solid #cbd5e1;"><?= htmlspecialchars($stage['stage_order']) ?></div>
                                    </td>
                                    <td style="font-weight:600; font-size:1.05rem;"><?= htmlspecialchars($stage['name']) ?></td>
                                    <td>
                                        <?php if ($stage['status_name']): ?>
                                            <span class="badge" style="background: <?= htmlspecialchars($stage['status_color']) ?>22; color: <?= htmlspecialchars($stage['status_color']) ?>; border: 1px solid <?= htmlspecialchars($stage['status_color']) ?>44;">
                                                <?= htmlspecialchars($stage['status_name']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span style="color:#94a3b8; font-style:italic; font-size:0.85rem;">None</span>
                                        <?php endif; ?>
                                    </td>
                                    <td style="text-align: right;">
                                        <a href="lead_stages.php?edit=<?= $stage['id'] ?>&funnel_id=<?= $active_funnel_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_stages.php?delete=<?= $stage['id'] ?>&f_id=<?= $active_funnel_id ?>" onclick="return confirm('Delete this pipeline stage?');" 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 elseif ($active_funnel_id): ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #94a3b8; padding: 20px;">No stages assigned to this funnel yet.</td>
                            </tr>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #94a3b8; padding: 20px;">Select a funnel to see its stages.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<style>
@media (max-width: 900px) {
    .dashboard-content > div:not(.welcome-banner) {
        grid-template-columns: 1fr !important;
    }
    .welcome-banner {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 15px;
    }
}
</style>

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