<?php
// إعداد الاتصال بقاعدة البيانات
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Database connection failed: " . $conn->connect_error]));
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $uniqueId = $_GET['unique_id'] ?? null;
    $ip = $_GET['ip'] ?? null;

    if (!$uniqueId || !$ip) {
        error_log("Missing unique_id or IP. Received values - unique_id: $uniqueId, ip: $ip");
        echo json_encode(["status" => "error", "message" => "Missing unique_id or IP."]);
        exit;
    }

    // التحقق من وجود إعادة توجيه
    $stmt = $conn->prepare("SELECT redirect_url FROM user_redirects WHERE unique_id = ? AND ip = ?");
    if (!$stmt) {
        error_log("Failed to prepare statement: " . $conn->error);
        echo json_encode(["status" => "error", "message" => "Failed to prepare statement."]);
        exit;
    }
    
    $stmt->bind_param("ss", $uniqueId, $ip);
    $stmt->execute();
    $stmt->bind_result($redirectUrl);
    
    if ($stmt->fetch()) {
        echo json_encode(["status" => "redirect", "redirect_url" => $redirectUrl]);
    } else {
        error_log("No redirect found for unique_id = $uniqueId and ip = $ip");
        echo json_encode(["status" => "no_redirect", "message" => "No redirect found."]);
    }

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