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

// Step 1: Include dependencies
include 'connection.php';
include 'decrypt_and_validate.php';   // AES-128-ECB decryption (Android input)
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC for DB storage
include '/home/screensh/private/privet_key.php';

$response = [];

try {
    // Step 2: Read POST data
    $name        = $_POST['Name'] ?? '';
    $email_enc   = $_POST['Email'] ?? '';
    $phone_enc   = $_POST['Phone_Number'] ?? '';
    $pass_enc    = $_POST['Password'] ?? '';
    $fcm_token   = $_POST['FCM_Token'] ?? '';
    $api_key     = $_POST['API_Key'] ?? '';

    // Step 3: Validate API key
    $validation = validateApiKey($api_key);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }

    // Step 4: Check required fields
    if (empty($name) || empty($email_enc) || empty($phone_enc) || empty($pass_enc) || empty($fcm_token)) {
        throw new Exception("All fields are required.");
    }

    // Step 5: Decrypt values from Android (AES-128-ECB)
    $email_plain = decryptData($email_enc);
    $phone_plain = decryptData($phone_enc);
    $pass_plain  = decryptData($pass_enc);

    if (!$email_plain || !$phone_plain || !$pass_plain) {
        throw new Exception("Decryption failed.");
    }

    // Step 6: Check if Phone exists (decrypt DB values before comparing)
    $stmt = $conn->prepare("SELECT Phone FROM User_Database");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $db_phone_plain = decryptSensitive($row['Phone']);
        if ($db_phone_plain === $phone_plain) {
            throw new Exception("Phone number already exists.");
        }
    }
    $stmt->close();

    // Step 7: Check if Email exists
    $stmt = $conn->prepare("SELECT Gmail FROM User_Database");
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $db_email_plain = decryptSensitive($row['Gmail']);
        if ($db_email_plain === $email_plain) {
            throw new Exception("Email already exists.");
        }
    }
    $stmt->close();

    // Step 8: Encrypt values for DB storage (AES-256-CBC)
    $email_db = encryptSensitive($email_plain);
    $phone_db = encryptSensitive($phone_plain);
    $pass_db  = encryptSensitive($pass_plain);

    // Step 9: Insert new user
    $joining_date   = date("Y-m-d");
    $total_bond_add = 0;
    $total_win_bond = 0;

    $stmt = $conn->prepare("INSERT INTO User_Database 
        (Name, Gmail, Phone, Passowrd, Joning_Date, Total_Bond_Add, Total_Win_Bond, FCM_Token) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssssiis", $name, $email_db, $phone_db, $pass_db, $joining_date, $total_bond_add, $total_win_bond, $fcm_token);

    if ($stmt->execute()) {
        $response = ["status" => "success", "message" => "Account created successfully."];
    } else {
        throw new Exception("Database insert failed: " . $stmt->error);
    }
    $stmt->close();

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

// Step 10: Return JSON response
echo json_encode($response);
?>
