<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require '../../../../db.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$data = json_decode(file_get_contents("php://input"));

if (
    !isset($data->name) || 
    !isset($data->diamonds) || 
    !isset($data->price)
) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Incomplete data.']);
    exit();
}

try {
    // TODO: Add Admin Authentication Check here

    if (isset($data->id) && !empty($data->id)) {
        // Update
        $sql = "UPDATE diamond_packages SET name = :name, diamonds = :diamonds, bonus = :bonus, price = :price, tag = :tag WHERE id = :id";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':id', $data->id);
    } else {
        // Create
        $sql = "INSERT INTO diamond_packages (name, diamonds, bonus, price, tag) VALUES (:name, :diamonds, :bonus, :price, :tag)";
        $stmt = $pdo->prepare($sql);
    }

    $bonus = isset($data->bonus) ? $data->bonus : 0;
    $tag = isset($data->tag) ? $data->tag : 'none';

    $stmt->bindValue(':name', $data->name);
    $stmt->bindValue(':diamonds', $data->diamonds);
    $stmt->bindValue(':bonus', $bonus);
    $stmt->bindValue(':price', $data->price);
    $stmt->bindValue(':tag', $tag);

    if ($stmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Package saved successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Unable to save package.']);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
