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

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 {
    $phone_enc = $_POST['Phone_Number'] ?? '';
    $pass_enc  = $_POST['Password'] ?? '';
    $api_key   = $_POST['API_Key'] ?? '';
    $fcm_token = $_POST['FCM_Token'] ?? '';

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

    if (empty($phone_enc) || empty($pass_enc)) {
        throw new Exception("Phone and Password are required.");
    }

    // Decrypt input
    $phone_plain = decryptData($phone_enc);
    $pass_plain  = decryptData($pass_enc);

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

    // Search DB
    $stmt = $conn->prepare("SELECT id, Phone, Passowrd FROM User_Database");
    $stmt->execute();
    $result = $stmt->get_result();

    $user_id = null;
    while ($row = $result->fetch_assoc()) {
        $db_phone_plain = decryptSensitive($row['Phone']);
        $db_pass_plain  = decryptSensitive($row['Passowrd']);

        if ($db_phone_plain === $phone_plain) {
            if ($db_pass_plain === $pass_plain) {
                $user_id = $row['id'];
            } else {
                throw new Exception("Invalid password.");
            }
        }
    }
    $stmt->close();

    if ($user_id) {
        // Update FCM token
        if (!empty($fcm_token)) {
            $stmt = $conn->prepare("UPDATE User_Database SET FCM_Token = ? WHERE id = ?");
            $stmt->bind_param("si", $fcm_token, $user_id);
            $stmt->execute();
            $stmt->close();
        }

        $response = ["status" => "success", "message" => "Login successful.", "user_id" => $user_id];
    } else {
        throw new Exception("Phone number not found.");
    }

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

echo json_encode($response);
?>
