<?php
// ✅ Start session before any output
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ✅ Check admin login
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

$jsonFile = 'assets/data/marketing-mockups.json';
$mockupDir = 'assets/mockups/';

// Load existing entries
$mockups = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

// Handle delete
if (isset($_GET['delete'])) {
    $deleteIndex = $_GET['delete'];
    if (isset($mockups[$deleteIndex])) {
        // Remove graphic file
        if (file_exists($mockups[$deleteIndex]['file'])) {
            unlink($mockups[$deleteIndex]['file']);
        }
        array_splice($mockups, $deleteIndex, 1);
        file_put_contents($jsonFile, json_encode($mockups, JSON_PRETTY_PRINT));
    }
    header("Location: admin-marketing-vault.php");
    exit;
}

// Handle add/update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $description = $_POST['description'] ?? '';
    $index = $_POST['index'] ?? -1;
    $filename = '';

    // Handle upload
    if (isset($_FILES['graphic']) && $_FILES['graphic']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['graphic']['name'], PATHINFO_EXTENSION);
        $safeName = strtolower(preg_replace('/[^a-zA-Z0-9\-_]/', '-', $description));
        $filename = $mockupDir . $safeName . '-' . uniqid() . '.' . $ext;
        move_uploaded_file($_FILES['graphic']['tmp_name'], $filename);
    } elseif ($index >= 0) {
        $filename = $mockups[$index]['file'];
    }

    $entry = [
        "description" => $description,
        "file" => $filename
    ];

    if ($index >= 0) {
        $mockups[$index] = $entry;
    } else {
        $mockups[] = $entry;
    }

    file_put_contents($jsonFile, json_encode($mockups, JSON_PRETTY_PRINT));
    header("Location: admin-marketing-vault.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Marketing Graphics</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4" style="display: flex; min-height: 100vh; margin: 0;">
  <div class="admin-sidebar" style="width:220px; background:#343a40; padding:20px;">
  <?php include 'google-translate-widget-front-end.php'; ?>
  <?php include 'admin-links.php'; ?>
</div>

  <div style="flex-grow: 1; padding: 20px;">
    <h2>🖼️ Upload Graphics to Marketing Vault</h2>

    <form action="" method="POST" enctype="multipart/form-data" class="mb-4">
        <div class="mb-2">
            <label class="form-label">Description</label>
            <input type="text" name="description" class="form-control" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Upload Graphic</label>
            <input type="file" name="graphic" class="form-control" accept=".png,.jpg,.jpeg" required>
        </div>
        <button class="btn btn-success">Add Graphic</button>
    </form>

    <h4>📂 Existing Vault Graphics</h4>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Preview</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($mockups as $i => $entry): ?>
            <tr>
                <td><img src="<?= $entry['file'] ?>" alt="mockup" style="width: 100px;"></td>
                <td><?= htmlspecialchars($entry['description']) ?></td>
                <td>
                    <form method="POST" enctype="multipart/form-data" style="display:inline-block;">
                        <input type="hidden" name="index" value="<?= $i ?>">
                        <input type="text" name="description" value="<?= htmlspecialchars($entry['description']) ?>" class="form-control mb-1" required>
                        <input type="file" name="graphic" class="form-control mb-1" accept=".png,.jpg,.jpeg">
                        <button class="btn btn-primary btn-sm mb-1">Update</button>
                    </form>
                    <a href="?delete=<?= $i ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this graphic?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php include 'admin-footer.php'; ?>

  </div>
</body>
</html>
