<?php
// Handle form submissions
if($_POST) {
    $name = $_POST['name'];
    $category = $_POST['category'];
    $price = $_POST['price'];
    $sale = $_POST['sale_price'] ?: null;
    $desc = $_POST['description'];
    $perks = json_encode(array_filter(explode("\n", $_POST['perks'])));
    $commands = json_encode(array_filter(explode("\n", $_POST['commands'])));
    $image = $_FILES['image']['name'] ?? '';

    if($image) {
        move_uploaded_file($_FILES['image']['tmp_name'], "../media/packages/$image");
        $image = "media/packages/$image";
    } else {
        $image = $pdo->query("SELECT image FROM packages WHERE id=".$_POST['id'])->fetchColumn();
    }

    if($_POST['id']) {
        $pdo->prepare("UPDATE packages SET name=?, category=?, price=?, sale_price=?, description=?, image=?, perks=?, commands=? WHERE id=?")
            ->execute([$name,$category,$price,$sale,$desc,$image,$perks,$commands,$_POST['id']]);
    } else {
        $pdo->prepare("INSERT INTO packages (name,category,price,sale_price,description,image,perks,commands) VALUES (?,?,?,?,?,?,?,?)")
            ->execute([$name,$category,$price,$sale,$desc,$image,$perks,$commands]);
    }
    echo '<div class="alert alert-success">Package saved!</div>';
}
?>
<h1>Packages</h1>
<a href="?page=packages&add=1" class="btn btn-success mb-3">Add New Package</a>

<?php if(isset($_GET['add']) || isset($_GET['edit'])): 
    $id = $_GET['edit'] ?? 0;
    $p = $id ? $pdo->query("SELECT * FROM packages WHERE id=$id")->fetch() : [];
?>
<form method="POST" enctype="multipart/form-data" class="card p-4">
    <input type="hidden" name="id" value="<?=$id?>">
    <div class="row">
        <div class="col-md-6">
            <input type="text" name="name" class="form-control mb-3" placeholder="Name" value="<?=htmlspecialchars($p['name']??'')?>" required>
            <input type="text" name="category" class="form-control mb-3" placeholder="Category (e.g. Ranks)" value="<?=htmlspecialchars($p['category']??'')?>" required>
            <input type="number" step="0.01" name="price" class="form-control mb-3" placeholder="Price" value="<?=$p['price']??''?>" required>
            <input type="number" step="0.01" name="sale_price" class="form-control mb-3" placeholder="Sale Price (optional)" value="<?=$p['sale_price']??''?>">
            <textarea name="description" class="form-control mb-3" rows="3" placeholder="Description"><?=htmlspecialchars($p['description']??'')?></textarea>
        </div>
        <div class="col-md-6">
            <input type="file" name="image" class="form-control mb-3" accept="image/*">
            <?php if(!empty($p['image'])): ?><img src="../<?=$p['image']?>" style="max-height:150px"><br><br><?php endif; ?>
            <textarea name="perks" class="form-control mb-3" rows="5" placeholder="One perk per line"><?=implode("\n", json_decode($p['perks']??'[]',true))?></textarea>
            <textarea name="commands" class="form-control mb-3" rows="5" placeholder="One command per line (use %username%)"><?=implode("\n", json_decode($p['commands']??'[]',true))?></textarea>
        </div>
    </div>
    <button class="btn btn-success">Save Package</button>
</form>
<?php else: ?>
<table class="table table-dark">
    <tr><th>Image</th><th>Name</th><th>Price</th><th>Category</th><th>Actions</th></tr>
    <?php foreach($pdo->query("SELECT * FROM packages ORDER BY id DESC") as $p): ?>
    <tr>
        <td><img src="../<?=htmlspecialchars($p['image'])?>" width="60"></td>
        <td><?=htmlspecialchars($p['name'])?></td>
        <td>$<?=$p['sale_price']?:$p['price']?></td>
        <td><?=htmlspecialchars($p['category'])?></td>
        <td>
            <a href="?page=packages&edit=<?=$p['id']?>" class="btn btn-warning btn-sm">Edit</a>
            <a href="?page=packages&del=<?=$p['id']?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete?')">Delete</a>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
<?php endif;

if(isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    $pdo->query("DELETE FROM packages WHERE id=$id");
    header("Location: ?page=packages");
}
?>