<?php
session_start();

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

$id = $_GET["id"] ?? null;
if (!$id) header("Location: index.php");

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


// Fetch Success Story first
$stmt = $pdo->prepare("SELECT * FROM case_studies WHERE id = ?");
$stmt->execute([$id]);
$case_study = $stmt->fetch();

if (!$case_study) exit("Success Story not found");

$title = $case_study["title"];
$content = $case_study["content"];
$imagePath = $case_study["featured_image"]; // now safe
$meta_title = $case_study["meta_title"] ?? '';
$meta_description = $case_study["meta_description"] ?? '';
$meta_keywords = $case_study["meta_keywords"] ?? '';

$error = "";

// Handle form submission
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"]);
    
    // Handle image upload if a new one is provided
    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 ($title && $content) {
        $slug = slugify($title);
        $stmt = $pdo->prepare("UPDATE case_studies SET title = ?, content = ?, slug = ?, featured_image = ?, meta_title = ?, meta_description = ?, meta_keywords = ? WHERE id = ?");
        $stmt->execute([$title, $content, $slug, $imagePath, $meta_title, $meta_description, $meta_keywords, $id]);                
      
        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>Edit 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">
  <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>Edit Success Story</h3>
<?php if ($error) echo "<div class='alert alert-danger'>$error</div>"; ?>

<form method="POST" enctype="multipart/form-data">
  <div class="mb-3">
    <label>Title</label>
    <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($title) ?>" 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 mb-2">
    <?php if ($imagePath): ?>
      <img src="../<?= $imagePath ?>" alt="Featured Image" width="150">
    <?php endif; ?>
  </div>

  <h6>SEO Tools</h6>
  <div class="mb-3">
  <label>Meta Title</label>
  <input type="text" name="meta_title" class="form-control" value="<?= htmlspecialchars($meta_title) ?>">
</div>

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

<div class="mb-3">
  <label>Meta Keywords</label>
  <input type="text" name="meta_keywords" class="form-control" value="<?= htmlspecialchars($meta_keywords) ?>">
</div>

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

  <button type="submit" class="btn btn-primary">Update</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>
</body>
</html>
