<?php
error_reporting(0);
header('Content-Type: application/json');
include 'config.php';
$conn->set_charset("utf8mb4");

session_start();

$action = $_POST['action'] ?? '';

// ---------- Admin Login API ----------
if ($action === 'login') {
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    
    $stmt = $conn->prepare("SELECT id FROM admin WHERE username=? AND password=? LIMIT 1");
    $stmt->bind_param("ss", $admin_username, $admin_password);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $_SESSION['admin_logged_in'] = true;
        echo json_encode(["status" => "success", "message" => "Login Successful"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid Admin Credentials!"]);
    }
    $stmt->close();
    exit;
}

// Authentication Check
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Access Denied. Please login."]);
    exit;
}

// ---------- GET ALL LIST ----------
if ($action === 'get_list') {
    $sql = "SELECT * FROM topup_list ORDER BY id DESC";
    $result = $conn->query($sql);
    $data = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    echo json_encode(["status" => "success", "data" => $data]);
    exit;
}

// ---------- GET SINGLE ITEM (For Edit) ----------
if ($action === 'get_single') {
    $id = (int)($_POST['id'] ?? 0);
    $stmt = $conn->prepare("SELECT * FROM topup_list WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($row = $result->fetch_assoc()) {
        echo json_encode(["status" => "success", "data" => $row]);
    } else {
        echo json_encode(["status" => "error", "message" => "Data not found"]);
    }
    $stmt->close();
    exit;
}

// ---------- ADD OR UPDATE ----------
if ($action === 'save') {
    $id = (int)($_POST['id'] ?? 0);
    $title = $_POST['title'] ?? '';
    $real_price = (float)($_POST['real_price'] ?? 0);
    $discount_price = (float)($_POST['discount_price'] ?? 0);
    $image_link = $_POST['image_link'] ?? '';
    $stock_message = $_POST['stock_message'] ?? '';

    if (empty($title)) {
        echo json_encode(["status" => "error", "message" => "Title is required!"]);
        exit;
    }

    if ($id > 0) {
        // UPDATE Logic
        $stmt = $conn->prepare("UPDATE topup_list SET title=?, real_price=?, discount_price=?, image_link=?, stock_message=? WHERE id=?");
        $stmt->bind_param("sddssi", $title, $real_price, $discount_price, $image_link, $stock_message, $id);
        $msg = "Topup updated successfully!";
    } else {
        // INSERT Logic
        $stmt = $conn->prepare("INSERT INTO topup_list (title, real_price, discount_price, image_link, stock_message) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sddss", $title, $real_price, $discount_price, $image_link, $stock_message);
        $msg = "New Topup added successfully!";
    }

    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => $msg]);
    } else {
        echo json_encode(["status" => "error", "message" => "Database Error: " . $stmt->error]);
    }
    $stmt->close();
    exit;
}

// ---------- DELETE ----------
if ($action === 'delete') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM topup_list WHERE id = ?");
        $stmt->bind_param("i", $id);
        if($stmt->execute()){
            echo json_encode(["status" => "success", "message" => "Item deleted successfully!"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to delete!"]);
        }
        $stmt->close();
    } else {
        echo json_encode(["status" => "error", "message" => "Invalid ID"]);
    }
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid Action Request"]);
$conn->close();
?>