<?php
header('Content-Type: application/json');
require "conn.php";
session_start();

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$response = ['success'=>false,'message'=>'Invalid request'];

/* 🔒 Security Check */
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['aW1iZXN0cmEuY29tLm15']) || $_SESSION['aW1iZXN0cmEuY29tLm15'] != $key) {
    echo json_encode(['success'=>false,'message'=>'Unauthorized']);
    exit;
}

/* 📦 List all products (for dropdown) */
if ($action === 'list') {
    $res = mysqli_query($con,"SELECT * FROM products ORDER BY product_name");
    $data = [];
    while($r=mysqli_fetch_assoc($res)) $data[]=$r;
    echo json_encode(['success'=>true,'data'=>$data]);
    exit;
}

/* 💾 Save */
if ($action === 'save') {
    $id = intval($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $price = floatval($_POST['price'] ?? 0);
    $qty_set = intval($_POST['qty_set'] ?? 0);
    $direct_sponsor = floatval($_POST['direct_sponsor'] ?? 0);
    $commission_level = intval($_POST['commission_level'] ?? 0);

    $items = [];
    if (!empty($_POST['product_id'])) {
        foreach($_POST['product_id'] as $i=>$pid) {
            $items[] = [
                'product_id' => intval($pid),
                'qty' => intval($_POST['qty'][$i] ?? 1),
                'cost_price' => floatval($_POST['cost_price'][$i] ?? 0)
            ];
        }
    }
    $items_json = json_encode($items, JSON_UNESCAPED_UNICODE);

    if ($id > 0) {
        $stmt = $con->prepare("UPDATE packages SET name=?, price=?, qty_set=?, direct_sponsor=?, commission_level=?, items=? WHERE id=?");
        $stmt->bind_param("sdiidsi", $name, $price, $qty_set, $direct_sponsor, $commission_level, $items_json, $id);
        $ok = $stmt->execute();
        $stmt->close();
        $response = $ok ? ['success'=>true,'message'=>'✅ Package updated successfully']
                        : ['success'=>false,'message'=>'❌ Failed to update package'];
    } else {
        $stmt = $con->prepare("INSERT INTO packages (name, price, qty_set, direct_sponsor, commission_level, items) VALUES (?,?,?,?,?,?)");
        $stmt->bind_param("sdiids", $name, $price, $qty_set, $direct_sponsor, $commission_level, $items_json);
        $ok = $stmt->execute();
        $stmt->close();
        $response = $ok ? ['success'=>true,'message'=>'✅ Package added successfully']
                        : ['success'=>false,'message'=>'❌ Failed to add package'];
    }
}

/* 🗑️ Delete */
elseif ($action === 'delete') {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) { echo json_encode(['success'=>false,'message'=>'Invalid package ID']); exit; }
    $del = mysqli_query($con,"DELETE FROM packages WHERE id=$id");
    $response = $del ? ['success'=>true,'message'=>'✅ Package deleted successfully']
                     : ['success'=>false,'message'=>'❌ Failed to delete package'];
}

echo json_encode($response);
?>
