<?php
session_start();

require_once "../../config/db.php";

$title = $content = "";
$error = "";

function slugify($text) {
  $text = preg_replace('~[^\pL\d]+~u', '-', $text);
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  $text = preg_replace('~[^-\w]+~', '', $text);
  $text = trim($text, '-');
  $text = preg_replace('~-+~', '-', $text);
  return strtolower($text);
}


$imagePath = null;
if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
    $uploadDir = '../uploads/';
    $imageName = time() . '-' . basename($_FILES['image']['name']);
    $targetPath = $uploadDir . $imageName;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
        $imagePath = 'uploads/' . $imageName;
    }
}


if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST["title"]);
    $content = trim($_POST["content"]);
    $meta_title = trim($_POST["meta_title"]);
    $meta_description = trim($_POST["meta_description"]);
    $meta_keywords = trim($_POST["meta_keywords"]);
    

    if ($title && $content) {
        $slug = slugify($title);
        $stmt = $pdo->prepare("INSERT INTO case_studies (title, content, slug, featured_image, meta_title, meta_description, meta_keywords) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $content, $slug, $imagePath, $meta_title, $meta_description, $meta_keywords]);        
         
        header("Location: index.php");
        exit;
    } else {
        $error = "Both fields are required.";
    }
}

if (!isset($_SESSION["admin_logged_in"])) {
  // Not logged in
  header("Location: /admin/login.php");
  exit;
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Create Success Story</title>
  <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/slick.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/responsive.css">

<!-- Use this if you don't want to register for an API key -->
<script src="https://cdn.jsdelivr.net/npm/tinymce@6.7.0/tinymce.min.js"></script>
<script>
  tinymce.init({
    selector: '#content',
    height: 400,
    menubar: false,
    plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table code help wordcount',
    toolbar: 'undo redo | blocks | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media | preview code fullscreen',
    branding: false
  });
</script>


</head>
<body>
    <div class="body-bg">
        <?php include '../includes/sidebar.php'; ?>
        <section class="nftmax-adashboard nftmax-show">
            <a href="index.php" class="btn btn-secondary mb-3">← Back to List</a>
            <h3>Create New List</h3>

            <?php if ($error) echo "<div class='alert alert-danger'>$error</div>"; ?>

            <form method="POST" onsubmit="return validateForm();" enctype="multipart/form-data">
            <div class="mb-3">
                <label>Title</label>
                <input type="text" name="title" class="form-control" required>
            </div>
            
            <div class="mb-3">
            <label>Featured Image</label>
            <p class="text-success">Preferred Dimension: 856x472</p>
            <input type="file" name="image" class="form-control">
            </div>
            <h6>SEO Tools</h6>
            <div class="mb-3">
            <label>Meta Title</label>
            <input type="text" name="meta_title" class="form-control">
            </div>

            <div class="mb-3">
            <label>Meta Description</label>
            <textarea name="meta_description" class="form-control" rows="2"></textarea>
            </div>

            <div class="mb-3">
            <label>Meta Keywords</label>
            <input type="text" name="meta_keywords" class="form-control" placeholder="e.g. app development, MVP company">
            </div>

            <div class="mb-3">
                <label>Content</label>
                <textarea id="content" name="content" class="form-control" rows="5"></textarea>

            </div>

            <button type="submit" class="btn btn-success">Publish</button>
            <a href="index.php" class="btn btn-secondary">Back</a>
            </form>

        </section>

    </div>

<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script>
    <script src="../assets/js/jquery-3.6.3.min.js"></script>
  <script src="../assets/js/slick.min.js"></script>
  <script src="../assets/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/js/chart.js"></script>
  <script src="../assets/js/custom.js"></script>
  <script src="../assets/js/modeControl.js"></script>
<script>
function validateForm() {
  const content = tinymce.get('content').getContent({ format: 'text' }).trim();
  if (content === "") {
    alert("Content field is required.");
    return false;
  }
  return true;
}
</script>


</body>
</html>
