<?php
require_once '../config.php';
require_once '../middleware.php';

### API Blueprint: /admin/app_settings
# GET /admin/app_settings?action=fetch
# Description: Fetches app settings.
# Headers:
#   - Admin-Token: <token>
# Parameters:
#   - action: string (required, value: fetch)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Settings fetched",
#       "data": {
#         "settings": {
#           "id": 1,
#           "claim_timer": 30,
#           "website_task_enabled": 0,
#           "referrer_coins": 50,
#           "referred_coins": 50,
#           "referral_coin_threshold": 500,
#           "daily_checkin_coins": 50,
#           "app_link": "https://example.com/app.apk",
#           "app_base_url": "https://example.com",
#           "version": "1.0.1",
#           "version_code": 2,
#           "changelogs": "Bug fixes",
#           "maintenance_mode": 0,
#           "vpn_allowed": 1,
#           "how_to_link": "https://example.com/how-to",
#           "telegram_link": "https://t.me/rewardapp",
#           "support_link": "https://example.com/support",
#           "privacy_policy_url": "https://example.com/privacy-policy",
#           "delete_url": "https://example.com/delete-account"
#         }
#       }
#     }
#   - 400: Invalid action
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/app_settings?action=update
# Description: Updates app settings.
# Headers:
#   - Admin-Token: <token>
# Parameters:
#   - action: string (required, value: update)
# Request Body:
#   - claim_timer: integer (required)
#   - website_task_enabled: integer (0 or 1, required)
#   - referrer_coins: integer (required)
#   - referred_coins: integer (required)
#   - referral_coin_threshold: integer (required)
#   - daily_checkin_coins: integer (required)
#   - app_link: string (required)
#   - app_base_url: string (required)
#   - version: string (required)
#   - version_code: integer (required)
#   - changelogs: string (required)
#   - maintenance_mode: integer (0 or 1, required)
#   - vpn_allowed: integer (0 or 1, required)
#   - how_to_link: string (required)
#   - telegram_link: string (required)
#   - support_link: string (required)
#   - privacy_policy_url: string (required)
#   - delete_url: string (required)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Settings updated"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/app_settings?action=update_partial
# Description: Updates specific app settings (partial update).
# Headers:
#   - Admin-Token: <token>
# Parameters:
#   - action: string (required, value: update_partial)
# Request Body:
#   - Any combination of the following fields (at least one required):
#     - claim_timer: integer (optional)
#     - website_task_enabled: integer (0 or 1, optional)
#     - referrer_coins: integer (optional)
#     - referred_coins: integer (optional)
#     - referral_coin_threshold: integer (optional)
#     - daily_checkin_coins: integer (optional)
#     - app_link: string (optional)
#     - app_base_url: string (optional)
#     - version: string (optional)
#     - version_code: integer (optional)
#     - changelogs: string (optional)
#     - maintenance_mode: integer (0 or 1, optional)
#     - vpn_allowed: integer (0 or 1, optional)
#     - how_to_link: string (optional)
#     - telegram_link: string (optional)
#     - support_link: string (optional)
#     - privacy_policy_url: string (optional)
#     - delete_url: string (optional)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Settings updated"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

# GET /admin/app_settings?action=fetch_ad_controls
# Description: Fetches all ad_controls rows.
# Headers:
#   - Admin-Token: <token>
# Parameters:
#   - action: string (required, value: fetch_ad_controls)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Ad controls fetched",
#       "data": {
#         "ad_controls": [
#           {
#             "id": 1,
#             "screen_name": "screen_name1",
#             "interstitial_ad": "https://example.com/interstitial1.jpg",
#             "banner_ad": "https://example.com/banner1.jpg",
#             "native_ad": "https://example.com/native1.jpg",
#             "reward_ad": "https://example.com/reward1.jpg",
#             "appopen_ad": "https://example.com/appopen1.jpg"
#           },
#           {
#             "id": 2,
#             "screen_name": "screen_name2",
#             "interstitial_ad": "https://example.com/interstitial2.jpg",
#             "banner_ad": "https://example.com/banner2.jpg",
#             "native_ad": "https://example.com/native2.jpg",
#             "reward_ad": "https://example.com/reward2.jpg",
#             "appopen_ad": "https://example.com/appopen2.jpg"
#           }
#         ]
#       }
#     }
#   - 400: Invalid action
#   - 401: Unauthorized
#   - 500: Database connection failed

# POST /admin/app_settings?action=update_ad_controls
# Description: Updates ad_controls for a given screen_name.
# Headers:
#   - Admin-Token: <token>
# Parameters:
#   - action: string (required, value: update_ad_controls)
# Request Body:
#   - screen_name: string (required)
#   - interstitial_ad: string (optional)
#   - banner_ad: string (optional)
#   - native_ad: string (optional)
#   - reward_ad: string (optional)
#   - appopen_ad: string (optional)
# Response:
#   - 200: Success
#     {
#       "status": 200,
#       "message": "Ad controls updated"
#     }
#   - 400: Invalid input
#   - 401: Unauthorized
#   - 500: Database connection failed

$admin_token = isset($_SERVER['HTTP_ADMIN_TOKEN']) ? $_SERVER['HTTP_ADMIN_TOKEN'] : '';
authenticateAdmin($admin_token);

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$conn = getDbConnection();

if ($method === 'GET' && $action === 'fetch') {
    $stmt = $conn->prepare("SELECT * FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->close();

    // Fetch ad_controls
    $stmt_adctrl = $conn->prepare("SELECT * FROM ad_controls");
    $stmt_adctrl->execute();
    $result_adctrl = $stmt_adctrl->get_result();
    $ad_controls = [];
    while ($row = $result_adctrl->fetch_assoc()) {
        $ad_controls[] = $row;
    }
    $stmt_adctrl->close();

    sendResponse(200, 'Settings fetched', [
        'settings' => $settings,
        'gamezop_card_status' => $settings['gamezop_card_status'],
        'ad_app_size' => $settings['ad_app_size'],
        'ad_controls' => $ad_controls
    ]);
} elseif ($method === 'POST' && $action === 'update') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    validateInput($data, [
        'claim_timer', 'website_task_enabled', 'referrer_coins', 'referred_coins',
        'referral_coin_threshold', 'daily_checkin_coins', 'app_link', 'app_base_url', 'version', 'version_code', 'changelogs',
        'maintenance_mode', 'vpn_allowed', 'how_to_link', 'telegram_link', 'support_link', 'privacy_policy_url', 'delete_url',
        'gamezop_card_status', 'ad_app_size', 'gamezop_timer', 'ad_index', 'earning_mode'
    ]);

    // Ensure integer fields are cast to int
    $data['gamezop_card_status'] = isset($data['gamezop_card_status']) ? (int)$data['gamezop_card_status'] : 1;
    $data['ad_app_size'] = isset($data['ad_app_size']) ? (int)$data['ad_app_size'] : null;
    $data['gamezop_timer'] = isset($data['gamezop_timer']) ? (int)$data['gamezop_timer'] : 10;
    $data['ad_index'] = isset($data['ad_index']) ? (int)$data['ad_index'] : 0;
    $data['earning_mode'] = isset($data['earning_mode']) ? (int)$data['earning_mode'] : 1;

    $stmt = $conn->prepare("UPDATE app_settings SET claim_timer = ?, website_task_enabled = ?, referrer_coins = ?, referred_coins = ?, referral_coin_threshold = ?, daily_checkin_coins = ?, app_link = ?, app_base_url = ?, version = ?, version_code = ?, changelogs = ?, maintenance_mode = ?, vpn_allowed = ?, how_to_link = ?, telegram_link = ?, support_link = ?, privacy_policy_url = ?, delete_url = ?, gamezop_card_status = ?, ad_app_size = ?, gamezop_timer = ?, ad_index = ?, earning_mode = ? WHERE id = 1");
    $stmt->bind_param(
        "iiiiisssssiisssssssiii",
        $data['claim_timer'],
        $data['website_task_enabled'],
        $data['referrer_coins'],
        $data['referred_coins'],
        $data['referral_coin_threshold'],
        $data['daily_checkin_coins'],
        $data['app_link'],
        $data['app_base_url'],
        $data['version'],
        $data['version_code'],
        $data['changelogs'],
        $data['maintenance_mode'],
        $data['vpn_allowed'],
        $data['how_to_link'],
        $data['telegram_link'],
        $data['support_link'],
        $data['privacy_policy_url'],
        $data['delete_url'],
        $data['gamezop_card_status'],
        $data['ad_app_size'],
        $data['gamezop_timer'],
        $data['ad_index'],
        $data['earning_mode']
    );
    $stmt->execute();

    sendResponse(200, 'Settings updated');
} elseif ($method === 'POST' && $action === 'update_partial') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    // Check if at least one field is provided
    $allowed_fields = [
        'claim_timer', 'website_task_enabled', 'referrer_coins', 'referred_coins',
        'referral_coin_threshold', 'daily_checkin_coins', 'app_link', 'app_base_url', 'version', 'version_code', 'changelogs',
        'maintenance_mode', 'vpn_allowed', 'how_to_link', 'telegram_link', 'support_link', 'privacy_policy_url', 'delete_url',
        'gamezop_card_status', 'ad_app_size', 'gamezop_timer', 'ad_index', 'earning_mode'
    ];

    // In update_partial, ensure integer fields are cast to int before binding
    foreach ($allowed_fields as $field) {
        if (isset($data[$field])) {
            if (in_array($field, ['claim_timer', 'website_task_enabled', 'referrer_coins', 'referred_coins', 'referral_coin_threshold', 'daily_checkin_coins', 'version_code', 'maintenance_mode', 'vpn_allowed', 'gamezop_card_status', 'ad_app_size', 'gamezop_timer', 'ad_index', 'earning_mode'])) {
                $data[$field] = (int)$data[$field];
            }
        }
    }

    $update_fields = [];
    $update_values = [];
    $update_types = '';

    foreach ($allowed_fields as $field) {
        if (isset($data[$field])) {
            $update_fields[] = "$field = ?";
            $update_values[] = $data[$field];
            
            // Determine the type for bind_param
            if (in_array($field, ['claim_timer', 'website_task_enabled', 'referrer_coins', 'referred_coins', 'referral_coin_threshold', 'daily_checkin_coins', 'version_code', 'maintenance_mode', 'vpn_allowed'])) {
                $update_types .= 'i'; // integer
            } else {
                $update_types .= 's'; // string
            }
        }
    }

    if (empty($update_fields)) {
        sendResponse(400, 'At least one field must be provided for update');
    }

    $sql = "UPDATE app_settings SET " . implode(', ', $update_fields) . " WHERE id = 1";
    $stmt = $conn->prepare($sql);
    
    if (!empty($update_values)) {
        $stmt->bind_param($update_types, ...$update_values);
    }
    
    $stmt->execute();

    sendResponse(200, 'Settings updated');
} elseif ($method === 'GET' && $action === 'fetch_ad_controls') {
    $stmt = $conn->prepare("SELECT * FROM ad_controls");
    $stmt->execute();
    $result = $stmt->get_result();
    $ad_controls = [];
    while ($row = $result->fetch_assoc()) {
        $ad_controls[] = $row;
    }
    $stmt->close();
    sendResponse(200, 'Ad controls fetched', ['ad_controls' => $ad_controls]);
} elseif ($method === 'POST' && $action === 'update_ad_controls') {
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }
    if (!isset($data['screen_name'])) {
        sendResponse(400, 'screen_name is required');
    }
    $fields = ['interstitial_ad', 'banner_ad', 'native_ad', 'reward_ad', 'appopen_ad'];
    $update_fields = [];
    $update_values = [];
    foreach ($fields as $field) {
        if (isset($data[$field])) {
            $update_fields[] = "$field = ?";
            $update_values[] = $data[$field];
        }
    }
    if (empty($update_fields)) {
        sendResponse(400, 'At least one ad field must be provided');
    }
    $update_values[] = $data['screen_name'];
    $sql = "UPDATE ad_controls SET ".implode(', ', $update_fields)." WHERE screen_name = ?";
    $stmt = $conn->prepare($sql);
    $types = str_repeat('i', count($update_fields)) . 's';
    $stmt->bind_param($types, ...$update_values);
    $stmt->execute();
    $stmt->close();
    sendResponse(200, 'Ad controls updated');
} else {
    sendResponse(400, 'Invalid action');
}

$stmt->close();
$conn->close();
?>