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

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;
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $image = $_FILES['image'];

    if ($name && $image['name']) {
        // Check real image info using getimagesize
        $image_info = getimagesize($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; // 5 MB

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

                // Load image resource based on actual mime type
                switch ($mime) {
                    case 'image/jpeg':
                        $img = imagecreatefromjpeg($image['tmp_name']);
                        break;
                    case 'image/png':
                        $img = imagecreatefrompng($image['tmp_name']);
                        break;
                    case 'image/gif':
                        $img = imagecreatefromgif($image['tmp_name']);
                        break;
                    case 'image/webp':
                        if (function_exists('imagecreatefromwebp')) {
                            $img = imagecreatefromwebp($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. Unsupported format or corrupted file.</div>";
                } else {
                    // Save image as JPG
                    if (imagejpeg($img, $target, 90)) {
                        imagedestroy($img);

                        $stmt = $pdo->prepare("INSERT INTO celebrities (name, slug, photo) VALUES (?, ?, ?)");
                        if ($stmt->execute([$name, $slug, $filename])) {
                            // Redirect to list_celebrity.php with success message
                            header('Location: list_celebrity.php?msg=added');
                            exit();
                        } else {
                            $message = "<div class='alert alert-danger'>Database error: Could not save celebrity.</div>";
                        }
                    } else {
                        imagedestroy($img);
                        $message = "<div class='alert alert-danger'>Failed to save image.</div>";
                    }
                }
            }
        }
    } else {
        $message = "<div class='alert alert-warning'>Please fill in all fields.</div>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Add Celebrity</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
  <style>
    body {
      background: #f1f3f7;
      font-family: system-ui, sans-serif;
      min-height: 100vh;
      margin: 0;
      padding: 0;
    }
    .content {
      margin-left: 260px;
      padding: 30px;
      max-width: 700px;
    }
    @media (max-width: 991.98px) {
      .content {
        margin-left: 0;
        padding: 20px 15px;
        padding-top: 70px; /* space for navbar on mobile */
      }
    }
    .form-label {
      font-weight: bold;
    }
  </style>
</head>
<body>

<?php include 'navbar.php'; ?>

<div class="content" role="main">
  <h2 class="mb-4">Add Celebrity</h2>
  <?= $message ?>

  <form method="POST" enctype="multipart/form-data" class="bg-white p-4 rounded shadow-sm">
    <div class="mb-3">
      <label for="name" class="form-label">Celebrity Name</label>
      <input type="text" name="name" id="name" class="form-control" placeholder="e.g., Wizkid" required />
    </div>

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

    <button type="submit" class="btn btn-primary">Add Celebrity</button>
  </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
