<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $position = $_POST['position'] ?? '';
    $bio = $_POST['bio'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $email = $_POST['email'] ?? '';
    $linkedin = $_POST['linkedin'] ?? '';
    $twitter = $_POST['twitter'] ?? '';
    $facebook = $_POST['facebook'] ?? '';
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE team_members SET name=?, position=?, bio=?, image_url=?, email=?, linkedin=?, twitter=?, facebook=?, sort_order=? WHERE id=?");
                $stmt->execute([$name, $position, $bio, $image_url, $email, $linkedin, $twitter, $facebook, $sort_order, $id]);
                $message = 'Team member updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO team_members (name, position, bio, image_url, email, linkedin, twitter, facebook, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $position, $bio, $image_url, $email, $linkedin, $twitter, $facebook, $sort_order]);
                $message = 'Team member added successfully.';
            }
        } catch (PDOException $e) {
            $message = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}

$team = $db->query("SELECT * FROM team_members ORDER BY sort_order ASC")->fetchAll();
$editMember = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM team_members WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editMember = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Team Members</h2>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3><?= $editMember ? 'Edit Team Member' : 'Add New Team Member' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editMember): ?>
        <input type="hidden" name="id" value="<?= $editMember['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" value="<?= htmlspecialchars($editMember['name'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Position</label>
            <input type="text" name="position" value="<?= htmlspecialchars($editMember['position'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Bio</label>
            <textarea name="bio" rows="4"><?= htmlspecialchars($editMember['bio'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editMember['image_url'] ?? '') ?>">
            <div style="margin-top:8px; display:flex; gap:8px; align-items:center;">
                <input type="file" id="file_upload_team_image" accept="image/*,.pdf" style="font-size:13px;">
                <button type="button" onclick="uploadFile('file_upload_team_image', 'image_url')" class="btn-sm btn-sm-success"><i class="fas fa-upload"></i> Upload</button>
                <span id="upload_status_file_upload_team_image" style="font-size:12px;color:#666;"></span>
            </div>
        </div>
        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" value="<?= htmlspecialchars($editMember['email'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>LinkedIn URL</label>
            <input type="url" name="linkedin" value="<?= htmlspecialchars($editMember['linkedin'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Twitter URL</label>
            <input type="url" name="twitter" value="<?= htmlspecialchars($editMember['twitter'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Facebook URL</label>
            <input type="url" name="facebook" value="<?= htmlspecialchars($editMember['facebook'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editMember['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editMember ? 'Update' : 'Add' ?> Team Member</button>
        <?php if ($editMember): ?>
        <a href="/admin/team" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Team Members</h3>
    <table>
        <thead>
            <tr><th>Image</th><th>Name</th><th>Position</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($team as $t): ?>
            <tr>
                <td><img src="<?= htmlspecialchars($t['image_url']) ?>" class="admin-img-preview"></td>
                <td><?= htmlspecialchars($t['name']) ?></td>
                <td><?= htmlspecialchars($t['position']) ?></td>
                <td><?= $t['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/team?edit=<?= $t['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="team_members"><input type="hidden" name="delete_id" value="<?= $t['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
