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

$message = '';

// Redirect if no id provided
if (!isset($_GET['id'])) {
    header("Location: list_celebrity.php");
    exit;
}

$id = (int)$_GET['id'];

// Fetch celebrity data
$stmt = $pdo->prepare("SELECT * FROM celebrities WHERE id = ?");
$stmt->execute([$id]);
$celeb = $stmt->fetch();

if (!$celeb) {
    header("Location: list_celebrity.php?msg=error");
    exit;
}

// Helper function to generate slug
function generate_slug($string) {
    $slug = strtolower($string);
    $slug = preg_replace('~[^\pL\d]+~u', '-', $slug);
    $slug = iconv('UTF-8', 'ASCII//TRANSLIT', $slug);
    $slug = preg_replace('~[^-\w]+~', '', $slug);
    $slug = trim($slug, '-');
    $slug = preg_replace('~-+~', '-', $slug);
    if (empty($slug)) {
        return 'n-a';
    }
    return $slug;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $slug = generate_slug($name);
    $photo = $celeb['photo'];

    if (!$name) {
        $message = "<div class='alert alert-warning'>Please enter the celebrity name.</div>";
    } else {
        $new_image_uploaded = isset($_FILES['image']) && $_FILES['image']['name'] !== '';

        if ($new_image_uploaded) {
            $image_info = getimagesize($_FILES['image']['tmp_name']);
            if ($image_info === false) {
                $message = "<div class='alert alert-danger'>Uploaded file is not a valid image.</div>";
            } else {
                $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $mime = $image_info['mime'];
                $max_size = 5 * 1024 * 1024;

                if (!in_array($mime, $allowed_types)) {
                    $message = "<div class='alert alert-danger'>Only JPG, PNG, GIF, and WEBP images are allowed.</div>";
                } elseif ($_FILES['image']['size'] > $max_size) {
                    $message = "<div class='alert alert-danger'>Image size must be less than 5 MB.</div>";
                } else {
                    $filename = $slug . '.jpg';
                    $target = '../images/' . $filename;

                    switch ($mime) {
                        case 'image/jpeg':
                            $img = imagecreatefromjpeg($_FILES['image']['tmp_name']);
                            break;
                        case 'image/png':
                            $img = imagecreatefrompng($_FILES['image']['tmp_name']);
                            break;
                        case 'image/gif':
                            $img = imagecreatefromgif($_FILES['image']['tmp_name']);
                            break;
                        case 'image/webp':
                            if (function_exists('imagecreatefromwebp')) {
                                $img = imagecreatefromwebp($_FILES['image']['tmp_name']);
                            } else {
                                $img = false;
                            }
                            break;
                        default:
                            $img = false;
                            break;
                    }

                    if ($img === false) {
                        $message = "<div class='alert alert-danger'>Failed to process the uploaded image.</div>";
                    } else {
                        if (imagejpeg($img, $target, 90)) {
                            imagedestroy($img);

                            // Delete old image if filename changed
                            if ($celeb['photo'] !== $filename) {
                                $old_path = '../images/' . $celeb['photo'];
                                if (file_exists($old_path)) {
                                    unlink($old_path);
                                }
                            }

                            $photo = $filename;
                        } else {
                            imagedestroy($img);
                            $message = "<div class='alert alert-danger'>Failed to save image.</div>";
                        }
                    }
                }
            }
        }

        if (empty($message)) {
            $update_stmt = $pdo->prepare("UPDATE celebrities SET name = ?, slug = ?, photo = ? WHERE id = ?");
            $res = $update_stmt->execute([$name, $slug, $photo, $id]);

            if ($res) {
                header("Location: list_celebrity.php?msg=updated");
                exit;
            } else {
                $message = "<div class='alert alert-danger'>Database error: Could not update celebrity.</div>";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Edit Celebrity</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body {
      background: #f1f3f7;
      min-height: 100vh;
      margin: 0;
      padding: 0;
      font-family: system-ui, sans-serif;
    }
    /* Sidebar styles for desktop */
    .sidebar {
      height: 100vh;
      position: fixed;
      width: 250px;
      background-color: #212529;
      padding-top: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      transition: transform 0.3s ease;
    }
    .sidebar h4 {
      color: #fff;
      margin-bottom: 2rem;
      user-select: none;
    }
    .sidebar a {
      color: #fff;
      text-decoration: none;
      display: block;
      width: 100%;
      padding: 15px 30px;
      transition: background-color 0.2s ease;
    }
    .sidebar a:hover,
    .sidebar a:focus {
      background-color: #343a40;
      outline: none;
    }
    /* Content margin to avoid sidebar */
    .content {
      margin-left: 260px;
      padding: 30px;
      max-width: 800px;
    }
    /* Celebrity photo */
    img.celeb-photo {
      max-width: 150px;
      max-height: 150px;
      object-fit: cover;
      border-radius: 8px;
      margin-bottom: 15px;
      display: block;
    }
    /* Responsive tweaks */
    @media (max-width: 991.98px) {
      /* Hide fixed sidebar on medium and smaller */
      .sidebar {
        display: none;
      }
      .content {
        margin-left: 0;
        padding: 20px 15px;
      }
    }
    /* Mobile navbar */
    .mobile-navbar {
      display: none;
      background-color: #212529;
      padding: 10px 15px;
      color: white;
      align-items: center;
      justify-content: space-between;
    }
    .mobile-navbar h4 {
      margin: 0;
      font-size: 1.25rem;
      user-select: none;
    }
    .mobile-navbar button {
      background: none;
      border: none;
      color: white;
      font-size: 1.5rem;
    }
    /* Show mobile navbar on small screens */
    @media (max-width: 991.98px) {
      .mobile-navbar {
        display: flex;
        position: fixed;
        width: 100%;
        top: 0;
        left: 0;
        z-index: 1050;
      }
      /* Push content below navbar */
      .content {
        padding-top: 70px;
      }
    }
    /* Mobile menu (hidden by default) */
    .mobile-menu {
      display: none;
      background-color: #212529;
      position: fixed;
      top: 50px;
      left: 0;
      width: 100%;
      z-index: 1040;
      flex-direction: column;
    }
    .mobile-menu a {
      color: white;
      padding: 15px 20px;
      border-top: 1px solid #343a40;
      text-decoration: none;
    }
    .mobile-menu a:hover,
    .mobile-menu a:focus {
      background-color: #343a40;
      outline: none;
    }
    /* Show mobile menu when active */
    .mobile-menu.show {
      display: flex;
    }
  </style>
</head>
<body>
<?php include 'navbar.php'; ?>


<!-- Sidebar for desktop -->
<div class="sidebar d-none d-lg-flex" role="navigation" aria-label="Sidebar navigation">
  <h4>Admin Panel</h4>
  <a href="admin_dashboard.php">Dashboard</a>
  <a href="add_celebrity.php">Add Celebrity</a>
  <a href="payroll.php">Payroll</a>
</div>

<div class="content" role="main">
  <h2>Edit Celebrity</h2>
  <?= $message ?>

  <form method="POST" enctype="multipart/form-data" class="bg-white p-4 rounded shadow-sm mx-auto" style="max-width: 600px;">
    <div class="mb-3">
      <label for="name" class="form-label">Celebrity Name</label>
      <input type="text" name="name" id="name" class="form-control" required value="<?= htmlspecialchars($celeb['name']) ?>">
    </div>

    <?php if (!empty($celeb['photo'])): ?>
      <div class="mb-3">
        <label class="form-label">Current Image</label><br />
        <img src="../images/<?= htmlspecialchars($celeb['photo']) ?>" alt="Current Image" class="celeb-photo" />
      </div>
    <?php endif; ?>

    <div class="mb-3">
      <label for="image" class="form-label">Upload New Image (optional)</label>
      <input type="file" name="image" id="image" class="form-control" accept="image/*">
    </div>

    <button type="submit" class="btn btn-primary">Update Celebrity</button>
    <a href="list_celebrity.php" class="btn btn-secondary ms-2">Back to List</a>
  </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  const toggleBtn = document.getElementById('mobile-menu-toggle');
  const mobileMenu = document.getElementById('mobile-menu');

  toggleBtn.addEventListener('click', () => {
    mobileMenu.classList.toggle('show');
  });
</script>

</body>
</html>
