<?php
// Disable error reporting for production
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);

define('ALLOWED_ACCESS', true);

// Verify includes
try {
    require_once '../../includes/config.php';
    require_once '../../includes/session.php';
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Server configuration error."]);
    exit;
}

// Check database connection
if (!$site_db || !$site_db instanceof mysqli || $site_db->connect_error) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Database connection failed."]);
    exit;
}

// Optional: Verify TopG IP (uncomment if needed)
/*
$topg_ip = gethostbyname('monitor.topg.org');
$ip_request = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if ($ip_request !== $topg_ip) {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Unauthorized request."]);
    exit;
}
*/

// Get and validate parameters
$p_resp  = isset($_GET['p_resp']) ? preg_replace('/[^A-Za-z0-9_-]/', '', $_GET['p_resp']) : null;
$user_ip = isset($_GET['ip']) ? filter_var($_GET['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) : null;

if (!$p_resp || !$user_ip || strlen($p_resp) > 32) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Invalid or missing parameters."]);
    exit;
}

// Find TopG site entry
$callback_file_name = 'topg';
$stmt = $site_db->prepare("SELECT id, reward_points, cooldown_hours FROM vote_sites WHERE callback_file_name = ? AND uses_callback = 1");
if (!$stmt || !$stmt->bind_param("s", $callback_file_name) || !$stmt->execute()) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Vote site lookup failed."]);
    exit;
}
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Vote site not found."]);
    exit;
}
$site = $result->fetch_assoc();
$internal_site_id = (int)$site['id'];
$reward_points    = (int)$site['reward_points'];
$cooldown_hours   = (int)$site['cooldown_hours'];
$stmt->close();

// Validate user
$stmt = $site_db->prepare("SELECT account_id FROM user_currencies WHERE username = ? OR account_id = ?");
if (!$stmt || !$stmt->bind_param("ss", $p_resp, $p_resp) || !$stmt->execute()) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "User validation failed."]);
    exit;
}
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "User not found."]);
    exit;
}
$row = $result->fetch_assoc();
$user_id = (int)$row['account_id'];
$stmt->close();

// Check cooldown
$can_vote = true;
$stmt = $site_db->prepare("
    SELECT vote_timestamp
    FROM vote_log
    WHERE user_id = ? AND site_id = ? AND reward_status = 0
    ORDER BY vote_timestamp DESC LIMIT 1
");
if ($stmt && $stmt->bind_param("ii", $user_id, $internal_site_id) && $stmt->execute()) {
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $last_vote = $result->fetch_assoc();
        $last_vote_time = (int)$last_vote['vote_timestamp'];
        $cooldown_seconds = $cooldown_hours * 3600;
        if (time() - $last_vote_time < $cooldown_seconds) {
            $can_vote = false;
        }
    }
    $stmt->close();
}

if (!$can_vote) {
    http_response_code(403);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "User is on cooldown."]);
    exit;
}

// Log the vote
$reward_status = 0; // Pending
$now = time();
$site_db->begin_transaction();
try {
    $stmt = $site_db->prepare("
        INSERT INTO vote_log (site_id, user_id, ip_address, vote_timestamp, reward_status)
        VALUES (?, ?, ?, ?, ?)
    ");
    if (!$stmt) throw new Exception();

    $stmt->bind_param("iisii", $internal_site_id, $user_id, $user_ip, $now, $reward_status);
    if (!$stmt->execute()) throw new Exception();
    $stmt->close();

    $site_db->commit();
    http_response_code(200);
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "success",
        "message" => "Vote logged successfully for $p_resp (ID: $user_id).",
        "points_pending" => $reward_points
    ]);
} catch (Exception $e) {
    $site_db->rollback();
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(["status" => "error", "message" => "Error logging vote."]);
}

// Close database connections
$site_db->close();
$auth_db->close();
$world_db->close();
$char_db->close();
exit;
?>
