<?php
header('Content-Type: application/json; charset=utf-8');

include 'connection.php';
include '/home/screensh/private/encryption_helper.php';
include '/home/screensh/private/privet_key.php';
include 'decrypt_and_validate.php';

$response = [];

try {
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';

    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);

    $validation = validateApiKey($apiKey);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }
    if (empty($userId)) {
        throw new Exception("User ID required");
    }

    // 1. Total bonds added
    $stmt = $conn->prepare("SELECT Bond_Series, Bond_Number, Bond_Add_Date 
                            FROM User_Bond_Add_History WHERE User_ID = ?");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $totalBonds = 0;
    $matchCount = 0;

    while ($row = $result->fetch_assoc()) {
        $series = decryptSensitive($row['Bond_Series'], $GLOBALS['PRIVATE_KEY']);
        $number = decryptSensitive($row['Bond_Number'], $GLOBALS['PRIVATE_KEY']);
        $totalBonds++;

        // Check match in Past_Draw_History
        $checkStmt = $conn->prepare("SELECT COUNT(*) as cnt 
                                     FROM Past_Draw_History 
                                     WHERE Winner_Bond_Number = ?");
        $checkStmt->bind_param("s", $number);
        $checkStmt->execute();
        $checkRes = $checkStmt->get_result();
        $cntRow = $checkRes->fetch_assoc();
        if ($cntRow['cnt'] > 0) {
            $matchCount++;
        }
        $checkStmt->close();
    }
    $stmt->close();

    // 2. Get joining date
    $stmt2 = $conn->prepare("SELECT Joning_Date FROM User_Database WHERE id = ?");
    $stmt2->bind_param("s", $userId);
    $stmt2->execute();
    $res2 = $stmt2->get_result();
    $joiningDate = null;
    if ($row2 = $res2->fetch_assoc()) {
        $joiningDate = $row2['Joning_Date'];
    }
    $stmt2->close();

    // 3. Calculate time since joining
    $timeDiffText = "";
    if ($joiningDate) {
        $join = new DateTime($joiningDate);
        $now  = new DateTime();
        $interval = $join->diff($now);

        if ($interval->y > 0) {
            $timeDiffText = $interval->y . " YEARS";
        } elseif ($interval->m > 0) {
            $timeDiffText = $interval->m . " MONTHS";
        } else {
            $timeDiffText = $interval->d . " DAYS";
        }
    }

    $response = [
        "status" => "success",
        "total_bonds" => $totalBonds,
        "total_matches" => $matchCount,
        "joining_date" => $joiningDate,
        "time_since_joining" => $timeDiffText
    ];

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

echo json_encode($response);
?>
