<?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/share-codes.json';
$thumbDir = 'assets/share-code-thumbs/';

// Load existing share codes
$shareCodes = file_exists($jsonFile) ? json_decode(file_get_contents($jsonFile), true) : [];

// Handle delete
if (isset($_GET['delete'])) {
    array_splice($shareCodes, $_GET['delete'], 1);
    file_put_contents($jsonFile, json_encode($shareCodes, JSON_PRETTY_PRINT));
    header("Location: add-sharecode-admin.php");
    exit;
}

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

    // Handle thumbnail upload
    $thumbName = '';
    if (isset($_FILES['thumb']) && $_FILES['thumb']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['thumb']['name'], PATHINFO_EXTENSION);
        $safeName = strtolower(str_replace(' ', '-', $title));
        $thumbName = $thumbDir . $safeName . '.' . $ext;
        move_uploaded_file($_FILES['thumb']['tmp_name'], $thumbName);
    } elseif ($index >= 0) {
        // Keep existing thumbnail if not changed
        $thumbName = $shareCodes[$index]['thumb'];
    }

    $entry = [
        "title" => $title,
        "code" => $code,
        "thumb" => $thumbName
    ];

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

    file_put_contents($jsonFile, json_encode($shareCodes, JSON_PRETTY_PRINT));
    header("Location: add-sharecode-admin.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage Share Codes</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>📚 Add or Edit Share Codes</h2>

    <form action="" method="POST" enctype="multipart/form-data" class="mb-4">
        <div class="mb-2">
            <label class="form-label">Title</label>
            <input type="text" name="title" class="form-control" required>
        </div>
        <div class="mb-2">
            <label class="form-label">Code</label>
            <input type="text" name="code" class="form-control" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Thumbnail</label>
            <input type="file" name="thumb" class="form-control" accept=".png,.jpg,.jpeg" required>
        </div>
        <button class="btn btn-success">Add Share Code</button>
    </form>

    <h4>📝 Existing Share Codes</h4>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Thumb</th>
                <th>Title</th>
                <th>Code</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($shareCodes as $i => $sc): ?>
            <tr>
                <td><img src="<?= $sc['thumb'] ?>" alt="thumb" style="width: 80px;"></td>
                <td><?= htmlspecialchars($sc['title']) ?></td>
                <td><?= htmlspecialchars($sc['code']) ?></td>
                <td>
                    <form method="POST" enctype="multipart/form-data" style="display:inline-block;">
                        <input type="hidden" name="index" value="<?= $i ?>">
                        <input type="text" name="title" value="<?= htmlspecialchars($sc['title']) ?>" class="form-control mb-1" required>
                        <input type="text" name="code" value="<?= htmlspecialchars($sc['code']) ?>" class="form-control mb-1" required>
                        <input type="file" name="thumb" 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 entry?')">Delete</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php include 'admin-footer.php'; ?>

</div> <!-- Close main-content -->
</body>
</html>
