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

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

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

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

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

// Handle Delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM lead_sources WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: lead_sources.php?msg=deleted");
        exit;
    } catch (PDOException $e) {
        $error = "Cannot delete this source because it might be assigned to existing leads.";
    }
}

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

// Fetch list
$stmt = $pdo->query("SELECT * FROM lead_sources ORDER BY name ASC");
$sources = $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-bullseye"></i> Lead Sources</h2>
        <p>Manage the origins of your leads (e.g., Website, Walk-in, Referrals).</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 ?> Source</h3>
            <form action="lead_sources.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;">Source Name*</label>
                    <input type="text" name="name" value="<?= htmlspecialchars($edit_name) ?>" required style="width:100%; padding:10px 15px; border:1px solid var(--border); border-radius:6px; font-family:inherit;">
                </div>
                
                <button type="submit" name="save_source" 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 Source' : 'Add Source' ?>
                </button>
                <?php if ($form_action === 'Edit'): ?>
                    <a href="lead_sources.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>Source Name</th>
                            <th style="width: 120px; text-align: right;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($sources) > 0): ?>
                            <?php $sno = 1; foreach ($sources as $source): ?>
                                <tr>
                                    <td style="color:#64748b; font-size:0.9rem;">#<?= $sno++ ?></td>
                                    <td style="font-weight:600;"><?= htmlspecialchars($source['name']) ?></td>
                                    <td style="text-align: right;">
                                        <a href="lead_sources.php?edit=<?= $source['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_sources.php?delete=<?= $source['id'] ?>" onclick="return confirm('Are you sure you want to delete this source?');" 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 lead sources 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'; ?>
