<?php  
session_start();
header("Content-Type: application/json; charset=UTF-8");  

$config_paths = ['Config.php', 'config.php', '../Config.php', '../config.php'];
foreach ($config_paths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

if (!isset($conn) && isset($con)) {
    $conn = $con;
}

// ==========================================
// 🔴 SECURITY & PERMISSION CHECK (API Level)
// ==========================================
if (!isset($_SESSION['admin_user']) || !isset($_SESSION['admin_pass'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized access!"]);
    exit;
}

$admin_user = $_SESSION['admin_user'];
$admin_pass = $_SESSION['admin_pass'];

// Check 'modarator_permissions' table
$perm_stmt = $conn->prepare("SELECT database_editing FROM modarator_permissions WHERE username = ? AND password = ?");
$perm_stmt->bind_param("ss", $admin_user, $admin_pass);
$perm_stmt->execute();
$perm_result = $perm_stmt->get_result();

if ($perm_result->num_rows === 0) {
    echo json_encode(["status" => "error", "message" => "Admin access denied! Invalid credentials."]);
    exit;
}

$perm_row = $perm_result->fetch_assoc();
if ($perm_row['database_editing'] !== 'Yes') {
    echo json_encode(["status" => "error", "message" => "Permission Denied! You do not have Database Editing rights."]);
    exit;
}
$perm_stmt->close();
// ==========================================


/* =========================  
   TYPE DEFINITIONS  
========================= */  
$types = [  
    "Type1" => [  
        "bkash_number", "nagad_number", "rocket_number", "add_money_link",   
        "collect_room_link", "admin_support_link", "join_match_link",   
        "diamond_selling_link", "win_photo_upload_link", "min_deposit",   
        "min_withdraw", "referral_bonus", "min_firstdp", "maximumdp",   
        "maximumwd", "secretkey", "brandkey", "daily_limit", "apikey"  
    ],  
    "Type2" => [  
        "home_notice", "multiple_login", "version_code", "update_link",   
        "auto_pay", "api_key", "update_notice", "updated_on",   
        "closed_reason", "apikey", "application_status", "addmoney_open",   
        "withdraw_open", "withdraw_block_time" 
    ]  
];  

/* =========================  
   GET CURRENT SETTINGS (To Show in UI)
========================= */ 
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $result = $conn->query("SELECT * FROM appinfo WHERE id = 1 LIMIT 1");
    if ($result && $result->num_rows > 0) {
        echo json_encode(["status" => "success", "data" => $result->fetch_assoc()]);
    } else {
        echo json_encode(["status" => "error", "message" => "No data found!"]);
    }
    exit;
}

/* =========================  
   POST (UPDATE SETTINGS)
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'] ?? null;  
    
    // TYPE VALIDATION
    if (!$type || !isset($types[$type])) {  
        echo json_encode(["status" => "error", "message" => "Invalid or missing 'type'."]);  
        exit;  
    }  
    
    // PREPARE DATA FROM POST
    $fields = $types[$type];  
    $data = [];  
    foreach ($fields as $field) {  
        if (isset($_POST[$field])) {  
            $data[$field] = $conn->real_escape_string($_POST[$field]);  
        }  
    }  
    
    if (count($data) === 0) {  
        echo json_encode(["status" => "error", "message" => "No valid fields provided."]);  
        exit;  
    }  
    
    // CHECK IF ROW EXISTS & UPDATE/INSERT
    $check = $conn->query("SELECT id FROM appinfo WHERE id = 1");  
    
    if ($check->num_rows === 0) {  
        $columns = implode(", ", array_keys($data));  
        $values  = "'" . implode("', '", array_values($data)) . "'";  
        $sql = "INSERT INTO appinfo (id, $columns) VALUES (1, $values)";  
    } else {  
        $updates = [];  
        foreach ($data as $col => $val) {  
            $updates[] = "$col = '$val'";  
        }  
        $sql = "UPDATE appinfo SET " . implode(", ", $updates) . " WHERE id = 1";  
    }  
    
    // EXECUTE
    if ($conn->query($sql)) {  
        echo json_encode(["status" => "success", "message" => "$type Updated Successfully!"]);  
    } else {  
        echo json_encode(["status" => "error", "message" => "Database operation failed!"]);  
    }  
    $conn->close(); 
}
?>
