<?php
include 'header.php';

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$err = "";
$msg = "";
$celebrity = null;
$upload_dir = '../uploads/celebrities/';

// Ensure upload directory exists
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_celebrity'])) {
    $id = filter_var($_POST['id'], FILTER_VALIDATE_INT);
    if ($id === false) {
        $err = "Invalid celebrity ID";
    } else {
        // Sanitize and validate inputs
        $name = mysqli_real_escape_string($link, trim($_POST['name']));
        $category = mysqli_real_escape_string($link, trim($_POST['category']));
        $specialties = mysqli_real_escape_string($link, trim($_POST['specialties']));
        $rating = filter_var($_POST['rating'], FILTER_VALIDATE_FLOAT) ?: 0.0;
        $happy_fans = filter_var($_POST['happy_fans'], FILTER_VALIDATE_INT) ?: 0;
        $events_done = filter_var($_POST['events_done'], FILTER_VALIDATE_INT) ?: 0;
        $response_rate = filter_var($_POST['response_rate'], FILTER_VALIDATE_FLOAT) ?: 0.0;
        $about = mysqli_real_escape_string($link, trim($_POST['about']));
        $languages = mysqli_real_escape_string($link, trim($_POST['languages']));
        $response_time = mysqli_real_escape_string($link, trim($_POST['response_time']));
        $regular_fee = filter_var($_POST['regular_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;
        $vvip_fee = filter_var($_POST['vvip_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;
        $gold_fee = filter_var($_POST['gold_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;
        $vip_royal_fee = filter_var($_POST['vip_royal_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;
        $personal_meetup_fee = filter_var($_POST['personal_meetup_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;
        $event_booking_fee = filter_var($_POST['event_booking_fee'], FILTER_VALIDATE_FLOAT) ?: 0.00;

        // Handle image upload
        $image = isset($_POST['existing_image']) ? mysqli_real_escape_string($link, $_POST['existing_image']) : '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
            if (in_array($_FILES['image']['type'], $allowed_types) && $_FILES['image']['size'] <= 5 * 1024 * 1024) {
                $image_name = time() . '_' . basename($_FILES['image']['name']);
                $image_path = $upload_dir . $image_name;
                if (move_uploaded_file($_FILES['image']['tmp_name'], $image_path)) {
                    $image = $image_name; // Save only the file name
                } else {
                    $err = "Failed to upload image";
                }
            } else {
                $err = "Invalid image type or size";
            }
        }

        // Handle gallery images upload
        $gallery_images = isset($_POST['existing_gallery_images']) ? mysqli_real_escape_string($link, $_POST['existing_gallery_images']) : '';
        if (isset($_FILES['gallery_images']) && !empty($_FILES['gallery_images']['name'][0])) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
            $uploaded_images = [];
            foreach ($_FILES['gallery_images']['name'] as $key => $name) {
                if ($_FILES['gallery_images']['error'][$key] === UPLOAD_ERR_OK && in_array($_FILES['gallery_images']['type'][$key], $allowed_types) && $_FILES['gallery_images']['size'][$key] <= 5 * 1024 * 1024) {
                    $gallery_name = time() . '_' . $key . '_' . basename($name);
                    $gallery_path = $upload_dir . $gallery_name;
                    if (move_uploaded_file($_FILES['gallery_images']['tmp_name'][$key], $gallery_path)) {
                        $uploaded_images[] = $gallery_name; // Save only file name
                    }
                }
            }
            if (!empty($uploaded_images)) {
                $gallery_images = implode(',', $uploaded_images);
            }
        }

        // Update database
        if (empty($err)) {
            $update_query = "UPDATE celebrities SET 
                             name = ?, category = ?, specialties = ?, image = ?, rating = ?, happy_fans = ?, events_done = ?, response_rate = ?, 
                             about = ?, languages = ?, response_time = ?, regular_fee = ?, vvip_fee = ?, 
                             gold_fee = ?, vip_royal_fee = ?, personal_meetup_fee = ?, event_booking_fee = ?
                             WHERE id = ?";
            $stmt = mysqli_prepare($link, $update_query);
            if ($stmt) {
                mysqli_stmt_bind_param($stmt, "ssssdddisssddddddi",
                    $name, $category, $specialties, $image, $rating,
                    $happy_fans, $events_done, $response_rate,
                    $about, $languages, $response_time,
                    $regular_fee, $vvip_fee, $gold_fee, $vip_royal_fee,
                    $personal_meetup_fee, $event_booking_fee, $id
                );

                if (mysqli_stmt_execute($stmt)) {
                    $msg = "Celebrity updated successfully";
                } else {
                    $err = "Error updating celebrity: " . mysqli_error($link);
                }
                mysqli_stmt_close($stmt);
            } else {
                $err = "Error preparing query: " . mysqli_error($link);
            }
        }
    }
}

// Fetch celebrity data
if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    $err = "Invalid or missing celebrity ID";
} else {
    $id = intval($_GET['id']);
    $sql = "SELECT * FROM celebrities WHERE id = ?";
    $stmt = mysqli_prepare($link, $sql);
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        if ($result && mysqli_num_rows($result) > 0) {
            $celebrity = mysqli_fetch_assoc($result);
        } else {
            $err = "Celebrity not found";
        }
        mysqli_stmt_close($stmt);
    } else {
        $err = "Error preparing query: " . mysqli_error($link);
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Celebrity - Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .page-content {
            padding: 20px;
        }
        .celebrity-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            padding: 2rem;
        }
        .celebrity-card img {
            max-width: 100px;
            border-radius: 5px;
            margin: 5px;
        }
        .back-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.6rem 1.2rem;
            border-radius: 10px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .back-btn:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            color: white;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <main class="flex-grow-1" style="padding-top: 80px;">
        <?php if ($err): ?>
            <div class="container mt-3">
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($err); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            </div>
        <?php elseif ($msg): ?>
            <div class="container mt-3">
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($msg); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            </div>
        <?php endif; ?>

        <div class="page-content">
            <div class="container-fluid">
                <div class="mb-3">
                    <a href="index.php" class="back-btn">
                        <i class="fas fa-arrow-left"></i> Back to Celebrities
                    </a>
                </div>
                <?php if ($celebrity): ?>
                    <div class="celebrity-card">
                        <h4 class="mb-4">Edit Celebrity: <?php echo htmlspecialchars($celebrity['name'] ?? 'N/A'); ?></h4>
                        <form method="POST" action="" enctype="multipart/form-data">
                            <input type="hidden" name="id" value="<?php echo $celebrity['id']; ?>">
                            <input type="hidden" name="existing_image" value="<?php echo htmlspecialchars($celebrity['image'] ?? ''); ?>">
                            <input type="hidden" name="existing_gallery_images" value="<?php echo htmlspecialchars($celebrity['gallery_images'] ?? ''); ?>">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="name" class="form-label">Name</label>
                                        <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($celebrity['name'] ?? ''); ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="category" class="form-label">Category</label>
                                        <input type="text" class="form-control" id="category" name="category" value="<?php echo htmlspecialchars($celebrity['category'] ?? ''); ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="specialties" class="form-label">Specialties</label>
                                        <textarea class="form-control" id="specialties" name="specialties"><?php echo htmlspecialchars($celebrity['specialties'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="mb-3">
                                        <label for="image" class="form-label">Image</label>
                                        <input type="file" class="form-control" id="image" name="image" accept="image/jpeg,image/png,image/gif">
                                  
                                            <div class="mt-2"><img src="../uploads/celebrities/<?php echo htmlspecialchars($celebrity['image']); ?>" alt="Preview"></div>
                                      
                                    </div>
                                    <!--<div class="mb-3">-->
                                    <!--    <label for="meetup_fee" class="form-label">Meetup Fee (USD)</label>-->
                                    <!--    <input type="number" step="0.01" min="0" class="form-control" id="meetup_fee" name="meetup_fee" value="<?php echo number_format($celebrity['meetup_fee'] ?? 0, 2); ?>" required>-->
                                    <!--</div>-->
                                    <!--<div class="mb-3">-->
                                    <!--    <label for="event_fee" class="form-label">Event Fee (USD)</label>-->
                                    <!--    <input type="number" step="0.01" min="0" class="form-control" id="event_fee" name="event_fee" value="<?php echo number_format($celebrity['event_fee'] ?? 0, 2); ?>" required>-->
                                    <!--</div>-->
                                    <div class="mb-3">
                                        <label for="rating" class="form-label">Rating</label>
                                        <input type="number" step="0.1" min="0" max="5" class="form-control" id="rating" name="rating" value="<?php echo number_format($celebrity['rating'] ?? 0, 1); ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="happy_fans" class="form-label">Happy Fans</label>
                                        <input type="number" min="0" class="form-control" id="happy_fans" name="happy_fans" value="<?php echo $celebrity['happy_fans'] ?? 0; ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="events_done" class="form-label">Events Done</label>
                                        <input type="number" min="0" class="form-control" id="events_done" name="events_done" value="<?php echo $celebrity['events_done'] ?? 0; ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="response_rate" class="form-label">Response Rate (%)</label>
                                        <input type="number" step="0.1" min="0" max="100" class="form-control" id="response_rate" name="response_rate" value="<?php echo number_format($celebrity['response_rate'] ?? 0, 1); ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="about" class="form-label">About</label>
                                        <textarea class="form-control" id="about" name="about"><?php echo htmlspecialchars($celebrity['about'] ?? ''); ?></textarea>
                                    </div>
                                    <div class="mb-3">
                                        <label for="languages" class="form-label">Languages</label>
                                        <input type="text" class="form-control" id="languages" name="languages" value="<?php echo htmlspecialchars($celebrity['languages'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="response_time" class="form-label">Response Time</label>
                                        <input type="text" class="form-control" id="response_time" name="response_time" value="<?php echo htmlspecialchars($celebrity['response_time'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="regular_fee" class="form-label">Regular Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="regular_fee" name="regular_fee" value="<?php echo number_format($celebrity['regular_fee'] ?? 0, 2); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="vvip_fee" class="form-label">VVIP Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="vvip_fee" name="vvip_fee" value="<?php echo number_format($celebrity['vvip_fee'] ?? 0, 2); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="gold_fee" class="form-label">Gold Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="gold_fee" name="gold_fee" value="<?php echo number_format($celebrity['gold_fee'] ?? 0, 2); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="vip_royal_fee" class="form-label">VIP Royal Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="vip_royal_fee" name="vip_royal_fee" value="<?php echo number_format($celebrity['vip_royal_fee'] ?? 0, 2); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="personal_meetup_fee" class="form-label">Personal Meetup Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="personal_meetup_fee" name="personal_meetup_fee" value="<?php echo number_format($celebrity['personal_meetup_fee'] ?? 0, 2); ?>">
                                    </div>
                                    <div class="mb-3">
                                        <label for="event_booking_fee" class="form-label">Event Booking Fee (USD)</label>
                                        <input type="number" step="0.01" min="0" class="form-control" id="event_booking_fee" name="event_booking_fee" value="<?php echo number_format($celebrity['event_booking_fee'] ?? 0, 2); ?>">
                                    </div>
                                   
                                </div>
                            </div>
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary" name="edit_celebrity">Save Changes</button>
                            </div>
                        </form>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning text-center">
                        No celebrity data available.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>

    <?php include 'footer.php'; ?>
</body>
</html>