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

// Handle Delete — must redirect BEFORE header.php outputs HTML
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $pdo->prepare("DELETE FROM lead_statuses WHERE id = ?")->execute([$id]);
        header("Location: lead_statuses.php?msg=deleted");
        exit;
    } catch (PDOException $e) {
        $del_error = "Cannot delete this status because it is assigned to existing leads.";
    }
}

require_once 'includes/header.php';

// Handle Add/Edit
$edit_id    = null;
$edit_name  = '';
$edit_color = '#64748b';
$form_action = 'Add New';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_status'])) {
    $name       = trim($_POST['name']);
    $color_code = trim($_POST['color_code']);
    $id         = !empty($_POST['id']) ? (int)$_POST['id'] : null;
    if (!empty($name)) {
        try {
            if ($id) {
                $pdo->prepare("UPDATE lead_statuses SET name=?, color_code=? WHERE id=?")->execute([$name, $color_code, $id]);
                $success = "Status updated successfully.";
            } else {
                $pdo->prepare("INSERT INTO lead_statuses (name, color_code) VALUES (?,?)")->execute([$name, $color_code]);
                $success = "Status added successfully.";
            }
            $edit_id = null; $edit_name = ''; $edit_color = '#64748b'; $form_action = 'Add New';
        } catch (PDOException $e) { $error = "Database error: " . $e->getMessage(); }
    } else { $error = "Name is required."; }
}

if (isset($_GET['msg']) && $_GET['msg'] === 'deleted') $success = "Status deleted successfully.";
if (isset($del_error)) $error = $del_error;

// Fetch list
$statuses = $pdo->query("SELECT * FROM lead_statuses ORDER BY name ASC")->fetchAll();
?>


<div class="dashboard-content">
    <div class="welcome-banner" style="margin-bottom: 20px; padding: 20px;">
        <h2><i class="fa-solid fa-tags"></i> Lead Statuses</h2>
        <p>Manage lead states and their visual color codes.</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 ?> Status</h3>
            <form action="lead_statuses.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;">Status Name*</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($edit_name) ?>" required placeholder="e.g. Hot Lead" 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;">Color Code</label>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <input type="color" name="color_code" value="<?= htmlspecialchars($edit_color) ?>" style="width:50px; height:40px; padding:2px; border:1px solid var(--border); border-radius:6px; cursor:pointer;">
                        <span style="font-size: 0.85rem; color:#64748b;">Pick a visual badge color</span>
                    </div>
                </div>
                
                <button type="submit" name="save_status" 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 Status' : 'Add Status' ?>
                </button>
                <?php if ($form_action === 'Edit'): ?>
                    <a href="lead_statuses.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>Status Name</th>
                            <th>Preview</th>
                            <th style="width: 120px; text-align: right;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($statuses) > 0): ?>
                            <?php $sno = 1; foreach ($statuses as $stat): ?>
                                <tr>
                                    <td style="color:#64748b; font-size:0.9rem;">#<?= $sno++ ?></td>
                                    <td style="font-weight:600;"><?= htmlspecialchars($stat['name']) ?></td>
                                    <td>
                                        <span class="badge" style="background-color: <?= htmlspecialchars($stat['color_code']) ?>20; color: <?= htmlspecialchars($stat['color_code']) ?>; border: 1px solid <?= htmlspecialchars($stat['color_code']) ?>50;">
                                            <?= htmlspecialchars($stat['name']) ?>
                                        </span>
                                    </td>
                                    <td style="text-align: right;">
                                        <a href="lead_statuses.php?edit=<?= $stat['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_statuses.php?delete=<?= $stat['id'] ?>" onclick="return confirm('Are you sure you want to delete this status?');" 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="4" style="text-align: center; color: #94a3b8; padding: 20px;">No lead statuses 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'; ?>
