<?php
/**
 * Admin - Edit Team Member
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Edit Team Member';
$member_id = intval($_GET['id'] ?? 0);
$member = null;
$errors = [];

if ($member_id) {
    try {
        $stmt = db()->prepare("SELECT * FROM team_members WHERE id = ?");
        $stmt->execute([$member_id]);
        $member = $stmt->fetch();
    } catch (PDOException $e) {}
}

if (!$member) {
    redirect(BASE_URL . 'admin/team-members.php', 'error', 'Team member not found');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        $name = sanitize($_POST['name'] ?? '');
        $designation = sanitize($_POST['designation'] ?? '');
        $bio = sanitize($_POST['bio'] ?? '');
        $sort_order = intval($_POST['sort_order'] ?? 0);
        $status = isset($_POST['status']) ? 1 : 0;
        
        if (empty($name)) $errors[] = 'Name is required';
        if (empty($designation)) $errors[] = 'Designation is required';
        
        // Handle image upload
        $image = $member['image'];
        if (!empty($_FILES['image']['name'])) {
            $upload = upload_file($_FILES['image'], 'team', ALLOWED_IMAGE_TYPES);
            if ($upload['success']) {
                // Delete old image
                if ($member['image'] && file_exists(UPLOADS_PATH . $member['image'])) {
                    unlink(UPLOADS_PATH . $member['image']);
                }
                $image = $upload['path'];
            } else {
                $errors[] = $upload['message'];
            }
        }
        
        if (empty($errors)) {
            try {
                $stmt = db()->prepare("UPDATE team_members SET 
                    name = ?, designation = ?, bio = ?, image = ?, sort_order = ?, status = ?, updated_at = NOW()
                    WHERE id = ?");
                $stmt->execute([$name, $designation, $bio, $image, $sort_order, $status, $member_id]);
                
                $stmt = db()->prepare("SELECT * FROM team_members WHERE id = ?");
                $stmt->execute([$member_id]);
                $member = $stmt->fetch();
                
                $success = 'Team member updated successfully';
            } catch (PDOException $e) {
                $errors[] = 'Failed to update member: ' . $e->getMessage();
            }
        }
    }
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Edit Team Member</h2>
    <a href="team-members.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-2"></i>Back</a>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger"><?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?></div>
<?php endif; ?>
<?php if (isset($success)): ?>
    <div class="alert alert-success"><?php echo $success; ?></div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            <div class="row g-3">
                <div class="col-md-2 text-center">
                    <?php if ($member['image']): ?>
                        <img src="<?php echo UPLOADS_URL . $member['image']; ?>" alt="" style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%;">
                    <?php else: ?>
                        <div style="width: 100px; height: 100px; background: #eee; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto;">
                            <i class="bi bi-person text-muted" style="font-size: 40px;"></i>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-10">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name <span class="text-danger">*</span></label>
                            <input type="text" name="name" class="form-control" value="<?php echo $member['name']; ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Designation <span class="text-danger">*</span></label>
                            <input type="text" name="designation" class="form-control" value="<?php echo $member['designation']; ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Change Photo</label>
                            <input type="file" name="image" class="form-control" accept="image/*">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Sort Order</label>
                            <input type="number" name="sort_order" class="form-control" value="<?php echo $member['sort_order']; ?>">
                        </div>
                        <div class="col-md-3">
                            <div class="form-check mt-4">
                                <input type="checkbox" name="status" class="form-check-input" id="statusCheck" <?php echo $member['status'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="statusCheck">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-12">
                    <label class="form-label">Bio</label>
                    <textarea name="bio" class="form-control" rows="4"><?php echo $member['bio']; ?></textarea>
                </div>
            </div>
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Update Member</button>
                <a href="team-members.php" class="btn btn-outline-secondary ms-2">Cancel</a>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
