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

include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC encrypt/decrypt
include '/home/screensh/private/privet_key.php';
include 'decrypt_and_validate.php';                     // AES-128-ECB decrypt for Android input

$response = [];

try {
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';
    $current_pass   = $_POST['Current_Password'] ?? '';
    $newPass_   = $_POST['New_Password'] ?? '';

    // Decrypt incoming values
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);
       $current = decryptData($current_pass);
          $newPass = decryptData($newPass_);

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

    // Step 1: Get encrypted password from DB
    $stmt = $conn->prepare("SELECT Passowrd FROM User_Database WHERE id = ?");
    $stmt->bind_param("s", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        // Decrypt stored password
        $dbPassword = decryptSensitive($row['Passowrd'], $GLOBALS['PRIVATE_KEY']);

        // Compare with provided current password
        if ($dbPassword !== $current) {
            throw new Exception("Current password is incorrect.");
        }

        // Step 2: Encrypt new password before storing
        $newPassEnc = encryptSensitive($newPass, $GLOBALS['PRIVATE_KEY']);

        $update = $conn->prepare("UPDATE User_Database SET Passowrd = ? WHERE id = ?");
        $update->bind_param("ss", $newPassEnc, $userId);

        if ($update->execute()) {
            $response = ["status" => "success", "message" => "Password updated successfully"];
        } else {
            throw new Exception("Failed to update password");
        }
        $update->close();
    } else {
        throw new Exception("User not found");
    }
    $stmt->close();

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

echo json_encode($response);
?>
